我正在尝试创建已使用该splice()函数添加的元素的实例。
var myFish = ['angels', 'clowns', 'starfish', 'sharks'];
var removed = myFish.splice(2,1, "spongebob");
console.log(removed); //
我正在寻找的输出是,spongebob但我得到了starfish.
有什么想法吗?
我正在尝试创建已使用该splice()函数添加的元素的实例。
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"]