簡體   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