我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
当前回答
我这样做:
const insert = (what, where, index) =>
([...where.slice(0, index), what , ...where.slice(index, where.length)]);
常量插入=(what,where,index)=>([…where.slice(0,index),what,…where.slice(index,where.length)]);常量列表=[1,2,3,4,5,6];const newList=插入('a',列表,2);console.log(newList.indexOf('a')==2);
其他回答
我喜欢一点安全,我用这个:
Array.prototype.Insert=函数(项,之前){if(!item)返回;if(before==null|| before<0|| before>this.length-1){this.push(项目);回来}此.拼接(之前,0,项);}var t=[“a”,“b”]t.插入(“v”,1)控制台日志(t)
您需要在本机阵列对象上使用拼接函数。
arr.splice(索引,0,项);将在指定的索引处向arr中插入项目(首先删除0个项目,也就是说,这只是一个插入)。
在本例中,我们将创建一个数组,并将一个元素添加到索引2中:
var arr=[];arr[0]=“Jani”;arr[1]=“Hege”;arr[2]=“过时”;arr[3]=“Kai Jim”;arr[4]=“博格”;console.log(arr.jjoin());//Jani、Hege、Stale、Kai Jim、Borgearr.splice(2,0,“Lene”);console.log(arr.jjoin());//Jani、Hege、Lene、Stale、Kai Jim、Borge
在特定索引处附加单个元素
// Append at a specific position (here at index 1)
arrName.splice(1, 0,'newName1');
// 1: index number, 0: number of element to remove, newName1: new element
// Append at a specific position (here at index 3)
arrName[3] = 'newName1';
在特定索引处附加多个元素
// Append from index number 1
arrName.splice(1, 0, 'newElemenet1', 'newElemenet2', 'newElemenet3');
// 1: index number from where append start,
// 0: number of element to remove,
//newElemenet1,2,3: new elements
自定义数组插入方法
1.具有多个参数和链接支持
/* Syntax:
array.insert(index, value1, value2, ..., valueN) */
Array.prototype.insert = function(index) {
this.splice.apply(this, [index, 0].concat(
Array.prototype.slice.call(arguments, 1)));
return this;
};
它可以插入多个元素(与原生拼接一样)并支持链接:
["a", "b", "c", "d"].insert(2, "X", "Y", "Z").slice(1, 6);
// ["b", "X", "Y", "Z", "c"]
2.支持数组类型参数合并和链接
/* Syntax:
array.insert(index, value1, value2, ..., valueN) */
Array.prototype.insert = function(index) {
index = Math.min(index, this.length);
arguments.length > 1
&& this.splice.apply(this, [index, 0].concat([].pop.call(arguments)))
&& this.insert.apply(this, arguments);
return this;
};
它可以将参数中的数组与给定数组合并,还支持链接:
["a", "b", "c", "d"].insert(2, "V", ["W", "X", "Y"], "Z").join("-");
// "a-b-V-W-X-Y-Z-c-d"
演示:http://jsfiddle.net/UPphH/
如果您想一次将多个元素插入到数组中,请查看以下堆栈溢出答案:用javascript将数组拼接到数组中的更好方法
下面还有一些函数来说明这两个示例:
function insertAt(array, index) {
var arrayToInsert = Array.prototype.splice.apply(arguments, [2]);
return insertArrayAt(array, index, arrayToInsert);
}
function insertArrayAt(array, index, arrayToInsert) {
Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
return array;
}
最后,这里有一个jsFiddle,您可以自己看到它:http://jsfiddle.net/luisperezphd/Wc8aS/
这是如何使用这些函数的:
// if you want to insert specific values whether constants or variables:
insertAt(arr, 1, "x", "y", "z");
// OR if you have an array:
var arrToInsert = ["x", "y", "z"];
insertArrayAt(arr, 1, arrToInsert);