如何将新项目“推”到数组中间?
这个问题在这里已经有了答案:
您可以使用Array.splice
将项目插入到特定位置的Array中。
const suits = ["hearts", "clubs", "Brooks Brothers", "diamonds", "spades"];
suits.splice(2, 0, 'newItem');
console.log(suits);
你应该使用拼接功能
arr.splice(index, 0, item);
将项目插入到指定索引的arr中(首先删除0个项目,即它只是一个插入)。
var suits = ["hearts","clubs","Brooks Brothers", "diamonds","spades"]
suits.splice(2, 0, "somevalue");
console.log(suits);
您可以使用内置的接头功能
splice()方法通过删除现有元素和/或添加新元素来更改数组的内容。
1-插入单个值
var suits = ["hearts","clubs","Brooks Brothers", "diamonds","spades"];
//1st param is insert index = 2 means insert at index 2
//2nd param is delete item count = 0 means delete 0 elements
//3rd param is new item that you want to insert
suits.splice(2, 0 , "Test");
console.log(suits);
链接地址: http://www.djcxy.com/p/29317.html