我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
当前回答
您可以使用splice()进行此操作
splice()方法在添加元素时通常会收到三个参数:
要添加项的数组的索引。要删除的项目数,在本例中为0。要添加的元素。
let array=['item 1','item 2','item 3']让insertAtIndex=0let itemsToRemove=0array.spling(insertAtIndex,itemsToRemove,'在索引0上插入此字符串')console.log(数组)
其他回答
var array= [10,20,30,40]
var i;
var pos=2; //pos=index + 1
/*pos is position which we want to insert at which is index + 1.position two in an array is index 1.*/
var value=5
//value to insert
//Initialize from last array element
for(i=array.length-1;i>=pos-1;i--){
array[i+1]=array[i]
}
array[pos-1]=value
console.log(array)
这是我在一个应用程序中使用的一个工作函数。
这将检查项目是否存在:
let ifExist = (item, strings = [ '' ], position = 0) => {
// Output into an array with an empty string. Important just in case their isn't any item.
let output = [ '' ];
// Check to see if the item that will be positioned exist.
if (item) {
// Output should be equal to an array of strings.
output = strings;
// Use splice() in order to break the array.
// Use positional parameters to state where to put the item
// and 0 is to not replace an index. Item is the actual item we are placing at the prescribed position.
output.splice(position, 0, item);
}
// Empty string is so we do not concatenate with comma or anything else.
return output.join("");
};
然后我把它叫做下面。
ifExist("friends", [ ' ( ', ' )' ], 1)} // Output: ( friends )
ifExist("friends", [ ' - '], 1)} // Output: - friends
ifExist("friends", [ ':'], 0)} // Output: friends:
我不得不同意Redu的回答,因为splice()的界面确实有点混乱。cdbajorin给出的响应是“当第二个参数为0时,它只返回一个空数组。如果它大于0,则返回从数组中删除的项“虽然准确,但证明了这一点。
该功能的目的是拼接,或者如Jakob Keller先前所说,“连接或连接,也改变。
您有一个已建立的阵列,现在正在更改,这将涉及添加或删除元素。。。。“考虑到这一点,被删除的元素(如果有的话)的返回值充其量是尴尬的。我100%同意,如果该方法返回了一个看起来很自然的新数组,添加了拼接元素,则该方法可能更适合于链接。然后,您可以对返回的数组执行类似[”19“,”17“].splice(1,0,”18“).join(”…“)之类的操作。
它返回删除的内容这一事实简直是无稽之谈。如果该方法的目的是“删除一组元素”,而这是它唯一的目的,也许。似乎如果我不知道我已经剪了什么,我可能没有什么理由剪掉这些元素,不是吗?
如果它表现得像concat()、map()、reduce()、slice()等,从现有数组生成新数组,而不是改变现有数组,那会更好。这些都是可链接的,这是一个重要的问题。链数组操作非常常见。
似乎语言需要朝一个或另一个方向发展,并尽可能地坚持下去。JavaScript具有功能性,声明性较低,这似乎是一种与规范的奇怪偏差。
多用途ARRAY和ARRAY OF OBJECT可重用方法
设arr=[0,1,2];让obj=〔{name:“abc”},{name::“xyz”};const addArrayItemAtIndex=(数组,索引,newItem)=>{return[…array.sslice(0,索引),newItem,…array.sSlice(索引)];}//对于阵列console.log(addArrayItemAtIndex(arr,2159));//对于对象阵列console.log(addArrayItemAtIndex(obj,0,{name:“AMOS”}));
不可变插入
如果您需要插入到阵列中的适当位置,使用拼接方法无疑是最佳答案。
但是,如果您正在寻找一个不可变函数,该函数返回一个新的更新数组,而不是在插入时对原始数组进行变异,那么可以使用以下函数。
函数插入(数组,索引){const items=Array.prototype.slice.call(arguments,2);return[].contat(array.sslice(0,索引),items,array.sslict(索引));}常量列表=['one','two','three'];const list1=插入(列表,0,“零”);//插入单个项目const list2=insert(列表,3,'four','five','sive');//插入多个console.log('原始列表:',列表);console.log('插入的列表1:',列表1);console.log('插入的列表2:',列表2);
注意:这是ES6之前的一种实现方式,因此它适用于较旧和较新的浏览器。
如果您使用的是ES6,那么您也可以尝试其他参数;看看这个答案。