Edward Casanova
Edward Casanova

Reputation: 964

How to Write An Instance Of an Added Element When Using array.splice()?

I'm trying to create an instance of the elements that have been added using the splice() function.

var myFish = ['angels', 'clowns', 'starfish', 'sharks'];
var removed = myFish.splice(2,1, "spongebob"); 
console.log(removed); // 

The output I'm looking for is spongebob but instead I get starfish.

Any thoughts?

Upvotes: 1

Views: 42

Answers (2)

sonEtLumiere
sonEtLumiere

Reputation: 4562

You are splicing by index 2 (starfish), remove 1 element and replace with 'spongebob'. starfish is removed and stored in removed var.

var myFish = ['angels', 'clowns', 'starfish', 'sharks'];
var removed = myFish.splice(2, 1, "spongebob");
console.log(myFish);  //["angels", "clowns", "spongebob", "sharks"]
console.log(myFish[2]); // spongebob
console.log(removed); // ["starfish"]

Upvotes: 0

ffritz
ffritz

Reputation: 2261

Array.splice returns the deleted elements, not the mutated array.

var myFish = ['angels', 'clowns', 'starfish', 'sharks'];
console.log("Array before we splice: ", myFish);
var removed = myFish.splice(2,1, "spongebob");
console.log("Array after we splice: ", myFish);
console.log("Replaced Element ", removed, "with: ", myFish[2]);

Upvotes: 2

Related Questions