首页 文章

如何在特定索引处将项插入数组?

提问于
浏览
2267

我正在寻找一种JavaScript数组插入方法,其格式为:

arr.insert(index, item)

最好是在jQuery中,但任何JavaScript实现都会在这一点上完成 .

12 回答

  • 32

    你想要的是本机数组对象上的 splice 函数 .

    arr.splice(index, 0, item);item 插入指定索引的 arr (首先删除 0 项,即它只是一个插入) .

    在这个例子中,我们将创建一个数组并将一个元素添加到索引2中:

    var arr = [];
    arr[0] = "Jani";
    arr[1] = "Hege";
    arr[2] = "Stale";
    arr[3] = "Kai Jim";
    arr[4] = "Borge";
    
    console.log(arr.join());
    arr.splice(2, 0, "Lene");
    console.log(arr.join());
    
  • 0

    您可以通过执行以下操作来实现 Array.insert 方法:

    Array.prototype.insert = function ( index, item ) {
        this.splice( index, 0, item );
    };
    

    然后你就可以使用它:

    var arr = [ 'A', 'B', 'D', 'E' ];
    arr.insert(2, 'C');
    
    // => arr == [ 'A', 'B', 'C', 'D', 'E' ]
    
  • 65

    即使已经回答了这个问题,我还是将这个说明添加到另一种方法中 .

    我想将一个 known number 项放入一个数组中,放入特定的位置,因为它们来自"associative array"(即一个对象),根据定义,它不能保证按排序顺序排列 . 我希望得到的数组是一个对象数组,但由于数组保证了它们的顺序,所以对象在数组中按特定的顺序排列 . 所以我这样做了 .

    首先是源对象,从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);
    
  • 3716

    自定义数组插入方法

    1.具有多个参数和链接支持

    /* Syntax:
       array.insert(index, value1, value2, ..., valueN) */
    
    Array.prototype.insert = function(index) {
        this.splice.apply(this, [index, 0].concat(
            Array.prototype.slice.call(arguments, 1)));
        return this;
    };
    

    它可以插入多个元素(原生splice)并支持链接:

    ["a", "b", "c", "d"].insert(2, "X", "Y", "Z").slice(1, 6);
    // ["b", "X", "Y", "Z", "c"]
    

    2.使用数组类型参数合并和链接支持

    /* Syntax:
       array.insert(index, value1, value2, ..., valueN) */
    
    Array.prototype.insert = function(index) {
        index = Math.min(index, this.length);
        arguments.length > 1
            && this.splice.apply(this, [index, 0].concat([].pop.call(arguments)))
            && this.insert.apply(this, arguments);
        return this;
    };
    

    它可以将参数中的数组与给定数组合并,并且还支持链接:

    ["a", "b", "c", "d"].insert(2, "V", ["W", "X", "Y"], "Z").join("-");
    // "a-b-V-W-X-Y-Z-c-d"
    

    DEMO: http://jsfiddle.net/UPphH/

  • 60

    另一种可能的解决方案,使用 Array#reduce .

    var arr = ["apple", "orange", "raspberry"],
        arr2 = [1, 2, 4];
    
    function insert(arr, item, index) {
        arr = arr.reduce(function(s, a, i) {
          i == index ? s.push(item, a) : s.push(a);
          return s;
        }, []);   
        console.log(arr);
    }
    
    insert(arr, "banana", 1);
    insert(arr2, 3, 2);
    
  • 15

    对于正确的函数编程和链接目的, Array.prototype.insert() 的发明是必不可少的 . 实际上,如果它已经返回变异数组而不是完全没有意义的空数组,那么splice可能是完美的 . 所以这就是它

    Array.prototype.insert = function(i,...rest){
      this.splice(i,0,...rest)
      return this
    }
    
    var a = [3,4,8,9];
    document.write("<pre>" + JSON.stringify(a.insert(2,5,6,7)) + "</pre>");
    

    好吧,上面的 Array.prototype.splice() 一个变异原始数组,有些人可能会抱怨"you shouldn't modify what doesn't belong to you",这可能也是正确的 . 因此,对于公益事业,我想给另一个 Array.prototype.insert() ,它不会改变原始阵列 . 在这里;

    Array.prototype.insert = function(i,...rest){
      return this.slice(0,i).concat(rest,this.slice(i));
    }
    
    var a = [3,4,8,9],
        b = a.insert(2,5,6,7);
    console.log(JSON.stringify(a));
    console.log(JSON.stringify(b));
    
  • 8

    任何人仍然有这个问题,并尝试了上述所有选项,从来没有得到它 . 我正在分享我的解决方案,这是为了考虑到你不要明确说明对象与数组的属性 .

    function isIdentical(left, right){
        return JSON.stringify(left) === JSON.stringify(right);
    }
    
    function contains(array, obj){
        let count = 0;
        array.map((cur) => {
              if(this.isIdentical(cur, obj)) count++;
        });
        return count > 0;
    }
    

    这是迭代参考数组并将其与您要检查的对象进行比较的组合,将它们转换为字符串然后迭代(如果匹配) . 然后你可以算一算 . 这可以改善,但这是我定居的地方 . 希望这可以帮助 .

  • 221

    如果要一次将多个元素插入到数组中,请查看此Stack Overflow答案:A better way to splice an array into an array in javascript

    这里还有一些函数来说明这两个例子:

    function insertAt(array, index) {
        var arrayToInsert = Array.prototype.splice.apply(arguments, [2]);
        return insertArrayAt(array, index, arrayToInsert);
    }
    
    function insertArrayAt(array, index, arrayToInsert) {
        Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
        return array;
    }
    

    最后这里是一个jsFiddle所以你可以为自己看到它:http://jsfiddle.net/luisperezphd/Wc8aS/

    这就是你如何使用这些功能:

    // if you want to insert specific values whether constants or variables:
    insertAt(arr, 1, "x", "y", "z");
    
    // OR if you have an array:
    var arrToInsert = ["x", "y", "z"];
    insertArrayAt(arr, 1, arrToInsert);
    
  • 5

    我建议在这种情况下使用纯 JavaScript ,在JavaScript中也没有插入方法,但是我们有一个方法,它是一个 built-in Array 方法,它为你完成了工作,它被称为 splice ...

    让's see what' s splice() ......

    splice()方法通过删除现有元素和/或添加新元素来更改数组的内容 .

    好的,想象我们下面有这个数组:

    const arr = [1, 2, 3, 4, 5];
    

    我们可以删除 3 这样:

    arr.splice(arr.indexOf(3), 1);
    

    它将返回3,但如果我们现在检查arr,我们有:

    [1, 2, 4, 5]
    

    到目前为止,这么好,但我们如何使用splice向阵列添加新元素?让我们回到3 ...

    arr.splice(2, 0, 3);
    

    让我们看看我们做了什么......

    我们再次使用 splice ,但这次是第二个参数,我们传递 0 ,意味着我们想要删除没有项目,但同时,我们添加第三个参数,它将在第二个索引处添加3 ...

    你应该知道,我们可以同时 deleteadd ,例如现在我们可以这样做:

    arr.splice(2, 2, 3);
    

    这将删除索引2处的 2 items ,然后在索引2处添加 3 ,结果将为:

    [1, 2, 3, 5];
    

    这显示了拼接中的每个项目如何工作:

    array.splice(start,deleteCount,item1,item2,item3 ......)

  • 2

    我试过这个,工作正常!

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

    索引是您要插入或删除元素的位置 . 0,即第二个参数定义要删除的索引中的元素数项是您要在数组中创建的新条目 . 它可以是一个或多个 .

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

    Append Single Element at a specific index

    //Append at specific position(here at index 1)
    arrName.splice(1, 0,'newName1');
    //1: index number, 0: number of element to remove, newName1: new element
    
    
    //Append at specific position (here at index 3)
    arrName[3] = 'newName1';
    

    Append Multiple Element at a specific index

    //Append from index number 1
    arrName.splice(1, 0,'newElemenet1', 'newElemenet2', 'newElemenet3');
    //1: index number from where append start, 
    //0: number of element to remove, 
    //newElemenet1,2,3: new elements
    
  • 3

    除了拼接,你可以使用这种方法不会改变原始数组,但会使用添加的项创建一个新数组 . 你应该尽可能避免变异 . 我在这里使用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]
    

    这可以用来添加多个项目,通过稍微调整函数来使用其余运算符来处理新项目,并将其传播到返回的结果中

    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]
    

相关问题