我正在寻找一个JavaScript数组插入方法,样式如下:

arr.insert(index, item)

最好是在jQuery中,但此时任何JavaScript实现都可以。


当前回答

下面是一个支持同时插入多个值的简单函数:

function add_items_to_array_at_position(array, index, new_items)
{
    return [...array.slice(0, index), ...new_items, ...array.slice(index)];
}

用法示例:

let old_array = [1,2,5];

let new_array = add_items_to_array_at_position(old_array, 2, [3,4]);

console.log(new_array);

//Output: [1,2,3,4,5]

其他回答

下面是一个支持同时插入多个值的简单函数:

function add_items_to_array_at_position(array, index, new_items)
{
    return [...array.slice(0, index), ...new_items, ...array.slice(index)];
}

用法示例:

let old_array = [1,2,5];

let new_array = add_items_to_array_at_position(old_array, 2, [3,4]);

console.log(new_array);

//Output: [1,2,3,4,5]

我这样做:

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);

这是我在一个应用程序中使用的一个工作函数。

这将检查项目是否存在:

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:

您需要在本机阵列对象上使用拼接函数。

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

您可以使用splice()进行此操作

splice()方法在添加元素时通常会收到三个参数:

要添加项的数组的索引。要删除的项目数,在本例中为0。要添加的元素。

let array=['item 1','item 2','item 3']让insertAtIndex=0let itemsToRemove=0array.spling(insertAtIndex,itemsToRemove,'在索引0上插入此字符串')console.log(数组)