[英]How to add a value to an array without the splice method and overwriting the element? javascript
Is there a way to concat an array at a specific index without overwriting the element, not using the splice method?有没有办法在特定索引处连接数组而不覆盖元素,而不是使用 splice 方法? I usually see concats happen in the beginning or end of an array.
我通常看到连接发生在数组的开头或结尾。
Below is an example of using splice to concat an array at an index下面是使用 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"]
```
You could take Array#copyWithin
with some adjustments.您可以对
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.