我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
当前回答
自定义数组插入方法
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/
其他回答
除了拼接,您可以使用这种方法,它不会改变原始数组,但会使用添加的项创建一个新数组。当你需要避免突变时,它是有用的。我在这里使用ES6排列运算符。
常量项=[1,2,3,4,5]常量插入=(arr,索引,newItem)=>[//数组的指定索引之前的部分…arr.slice(0,索引),//插入的项目新项目,//指定索引之后的数组的一部分…arr.slice(索引)]常量结果=插入(项,1,10)console.log(结果)// [1, 10, 2, 3, 4, 5]
这可以用于添加多个项目,方法是稍微调整函数,为新项目使用rest运算符,并在返回的结果中传播:
常量项=[1,2,3,4,5]常量插入=(arr,索引,…newItems)=>[//数组的指定索引之前的部分…arr.slice(0,索引),//插入的项目…新项目,//指定索引之后的数组的一部分…arr.slice(索引)]常量结果=插入(项,1,10,20)console.log(结果)// [1, 10, 20, 2, 3, 4, 5]
您可以使用array.spling执行此操作:
/**
* @param arr: Array
* @param item: item to insert
* @param index: index at which to insert
* @returns array with the inserted element
*/
export function _arrayInsertAt<T>(arr: T[], item: T, index: number) {
return arr.splice(index, 0, item);;
}
阵列切片的文档
另一种可能的解决方案,使用Array.reduce。
const arr=[“苹果”、“橙色”、“覆盆子”];常量arr2=[1,2,4];常量插入=(arr,项,索引)=>arr.reduce(函数,a,i){i==索引?s.push(项目,a):s.push(a);返回s;}, []);console.log(插入(arr,“香蕉”,1));控制台日志(插入(arr2,3,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)
按以下方式计算减少方法的利润:
function insert(arr, val, index) {
return index >= arr.length
? arr.concat(val)
: arr.reduce((prev, x, i) => prev.concat(i === index ? [val, x] : x), []);
}
因此,通过这种方式,我们可以返回一个新数组(这将是一种很酷的函数方式,比使用push或splice要好得多),其中元素插入索引处,如果索引大于数组长度,则将在末尾插入。