簡體   English   中英

如何在沒有 splice 方法的情況下向數組添加值並覆蓋元素? javascript

[英]How to add a value to an array without the splice method and overwriting the element? javascript

有沒有辦法在特定索引處連接數組而不覆蓋元素,而不是使用 splice 方法? 我通常看到連接發生在數組的開頭或結尾。

下面是使用 splice 在索引處連接數組的示例

var colors=["red","blue"];
var index=1;

//if i wanted to insert "white" at index 1
colors.splice(index, 0, "white");   //colors =  ["red", "white", "blue"]
```

您可以對Array#copyWithin進行一些調整。

 const colors = ["red", "blue"], index = 1, value = "white"; colors.length++; // create space for moving colors.copyWithin(index + 1, index); // move values to right colors[index] = value; // add new value console.log(colors); // ["red", "white", "blue"]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM