如何在没有拼接方法和覆盖元素的情况下向数组添加值? javascript

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

有没有办法在不覆盖元素的情况下在特定索引处连接数组,而不是使用拼接方法?我通常看到 concats 发生在数组的开头或结尾。

下面是使用 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"]