我正在寻找一种JavaScript数组插入方法,其风格为:
arr.insert(index, item)
最好在jQuery中,但此时任何JavaScript实现都可以。
网友回答:
您可以通过执行以下操作来实现该方法:Array.insert
Array.prototype.insert = function ( index, ...items ) {
this.splice( index, 0, ...items );
};
然后你可以像这样使用它:
var arr = [ 'A', 'B', 'E' ];
arr.insert(2, 'C', 'D');
// => arr == [ 'A', 'B', 'C', 'D', 'E' ]
网友回答:
您希望本机数组对象上的拼接
函数。
arr.splice(index, 0, item);
将插入到指定的位置(首先删除项目,即它只是一个插入)。item
arr
index
0
在这个例子中,我们将创建一个数组,并将一个元素添加到索引 2 中:
var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";
console.log(arr.join()); // Jani,Hege,Stale,Kai Jim,Borge
arr.splice(2, 0, "Lene");
console.log(arr.join()); // Jani,Hege,Lene,Stale,Kai Jim,Borge
网友回答:
除了拼接之外,您还可以使用这种方法,它不会改变原始数组,但它会创建一个包含添加项的新数组。当您需要避免突变时,它很有用。我在这里使用 ES6 点差运算符。
const items = [1, 2, 3, 4, 5]
const insert = (arr, index, newItem) => [
// part of the array before the specified index
...arr.slice(0, index),
// inserted item
newItem,
// part of the array after the specified index
...arr.slice(index)
]
const result = insert(items, 1, 10)
console.log(result)
// [1, 10, 2, 3, 4, 5]
这可用于添加多个项目,方法是稍微调整函数以对新项目使用 rest 运算符,并将其分散到返回的结果中:
const items = [1, 2, 3, 4, 5]
const insert = (arr, index, ...newItems) => [
// part of the array before the specified index
...arr.slice(0, index),
// inserted items
...newItems,
// part of the array after the specified index
...arr.slice(index)
]
const result = insert(items, 1, 10, 20)
console.log(result)
// [1, 10, 20, 2, 3, 4, 5]
模板简介:该模板名称为【JavaScript数组插入方法,其风格为:arr.insert(index, item) 最好在jQuery中实现都可以】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【JavaScript】栏目查找您需要的精美模板。