1

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

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

我正在寻找的输出是,spongebob但我得到了starfish.

有什么想法吗?

4

2 回答 2

2

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

于 2020-06-30T15:22:38.053 回答
0

您正在按索引 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"]

于 2020-06-30T15:24:38.993 回答