简体   繁体   English

使用 array.splice() 时如何编写添加元素的实例?

[英]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.我正在尝试创建使用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 .我正在寻找的spongebob是海绵宝宝,但我得到的是starfish

Any thoughts?有什么想法吗?

Array.splice returns the deleted elements, not the mutated array. Array.splice返回已删除的元素,而不是变异的数组。

 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'.您正在按索引 2(海星)进行拼接,删除 1 个元素并替换为“海绵宝宝”。 starfish is removed and stored in removed var.海星被删除并存储在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"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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