我正在寻找一个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' ]

其他回答

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

尽管这个问题已经得到了回答,但我还是添加了这个注释作为替代方法。

我想将已知数量的项目放入一个数组中,放入特定位置,因为它们来自一个“关联数组”(即一个对象),根据定义,该数组不能保证按排序顺序排列。我希望得到的数组是一个对象数组,但是对象在数组中的顺序是特定的,因为数组保证了它们的顺序。所以我这样做了。

首先是源对象,一个从PostgreSQL检索的JSONB字符串。我想让它按每个子对象中的“order”属性排序。

var jsonb_str = '{"one": {"abbr": "", "order": 3}, "two": {"abbr": "", "order": 4}, "three": {"abbr": "", "order": 5}, "initialize": {"abbr": "init", "order": 1}, "start": {"abbr": "", "order": 2}}';

var jsonb_obj = JSON.parse(jsonb_str);

由于对象中的节点数是已知的,因此我首先创建一个具有指定长度的数组:

var obj_length = Object.keys(jsonb_obj).length;
var sorted_array = new Array(obj_length);

然后迭代对象,将新创建的临时对象放置到数组中所需的位置,而不进行任何“排序”。

for (var key of Object.keys(jsonb_obj)) {
  var tobj = {};
  tobj[key] = jsonb_obj[key].abbr;

  var position = jsonb_obj[key].order - 1;
  sorted_array[position] = tobj;
}

console.dir(sorted_array);

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

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

我喜欢一点安全,我用这个:

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)

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

这将检查项目是否存在:

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: