简体   繁体   中英

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?

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]);

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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM