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

arr.insert(index, item)

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


当前回答

您可以使用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);; 
}

阵列切片的文档

其他回答

我试过了,效果很好!

var initialArr = ["India","China","Japan","USA"];
initialArr.splice(index, 0, item);

索引是要插入或删除元素的位置。

0,即第二个参数,定义要从索引中删除的元素的数量。项包含要在数组中创建的新条目。它可以是一个或多个。

initialArr.splice(2, 0, "Nigeria");
initialArr.splice(2, 0, "Australia","UK");

我不得不同意Redu的回答,因为splice()的界面确实有点混乱。cdbajorin给出的响应是“当第二个参数为0时,它只返回一个空数组。如果它大于0,则返回从数组中删除的项“虽然准确,但证明了这一点。

该功能的目的是拼接,或者如Jakob Keller先前所说,“连接或连接,也改变。

您有一个已建立的阵列,现在正在更改,这将涉及添加或删除元素。。。。“考虑到这一点,被删除的元素(如果有的话)的返回值充其量是尴尬的。我100%同意,如果该方法返回了一个看起来很自然的新数组,添加了拼接元素,则该方法可能更适合于链接。然后,您可以对返回的数组执行类似[”19“,”17“].splice(1,0,”18“).join(”…“)之类的操作。

它返回删除的内容这一事实简直是无稽之谈。如果该方法的目的是“删除一组元素”,而这是它唯一的目的,也许。似乎如果我不知道我已经剪了什么,我可能没有什么理由剪掉这些元素,不是吗?

如果它表现得像concat()、map()、reduce()、slice()等,从现有数组生成新数组,而不是改变现有数组,那会更好。这些都是可链接的,这是一个重要的问题。链数组操作非常常见。

似乎语言需要朝一个或另一个方向发展,并尽可能地坚持下去。JavaScript具有功能性,声明性较低,这似乎是一种与规范的奇怪偏差。

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

这将检查项目是否存在:

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:

Array#splice()是最好的方法,除非你真的想避免改变数组。给定2个数组arr1和arr2,下面是如何将arr2的内容插入到arr1的第一个元素之后:

常量arr1=[‘a’,‘d’,‘e’];常量arr2=['b','c'];arr1.拼接(1,0,…arr2);//arr1现在包含[a','b','c','d','e']控制台日志(arr1)

如果您担心数组的变异(例如,如果使用Immutable.js),可以改用slice(),不要与带有“p”的splice()混淆。

const arr3 = [...arr1.slice(0, 1), ...arr2, ...arr1.slice(1)];

按以下方式计算减少方法的利润:

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要好得多),其中元素插入索引处,如果索引大于数组长度,则将在末尾插入。