繁体   English   中英

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

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

我正在尝试创建使用splice() function 添加的元素的实例。

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

我正在寻找的spongebob是海绵宝宝,但我得到的是starfish

有什么想法吗?

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

您正在按索引 2(海星)进行拼接,删除 1 个元素并替换为“海绵宝宝”。 海星被删除并存储在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