Is there a way to use Array.splice in javascript with the third parameter as an array?

后端 未结 7 1761
悲哀的现实
悲哀的现实 2020-12-29 04:30

I\'m attempting the following:

var a1 = [\'a\', \'e\', \'f\'];  // [a, e, f]
var a2 = [\'b\', \'c\', \'d\'];  // [b, c, d]
a1.splice(1, 0, a2);       // expe         


        
相关标签:
7条回答
  • 2020-12-29 05:09
    var a1 = ['a', 'e', 'f'],
        a2 = ['b', 'c', 'd'];
    
    a1.splice(1, 0, a2);
    
    var flatten = [].concat.apply([], a1); // ["a", "b", "c", "d", "e", "f"]
    
    0 讨论(0)
  • Array.splice supports multiple arguments after the first two. Those arguments will all be added to the array. Knowing this, you can use Function.apply to pass the array as the arguments list.

    var a1 = ['a', 'e', 'f'];
    var a2 = ['b', 'c', 'd'];
    
    // You need to append `[1,0]` so that the 1st 2 arguments to splice are sent
    Array.prototype.splice.apply(a1, [1,0].concat(a2));
    
    0 讨论(0)
  • 2020-12-29 05:11

    This should do the trick.

    var a1 = ['a', 'e', 'f'];
    var a2 = ['b', 'c', 'd'];
    
    a1.concat(a2, a1.splice(1,a1.length-1)) // [a, b, c, d, e, f]
    
    0 讨论(0)
  • 2020-12-29 05:11

    Try this:

    var params = a2.slice(0);
    params.unshift(1,0);
    a1.splice.apply(a1,params);
    

    In the more general case:

    Array.prototype.splice_multi = function(offset,todelete,insert) {
        var params = insert.slice(0);
        params.unshift(offset,todelete);
        return this.splice.apply(this,params);
    };
    a1.splice_multi(1,0,a2);
    
    0 讨论(0)
  • 2020-12-29 05:23

    With ES6, you can use the spread operator. It makes it much more concise and readable.

    var a1 = ['a', 'e', 'f'];
    var a2 = ['b', 'c', 'd'];
    
    a1.splice(1, 0, ...a2);
    console.log(a1)

    0 讨论(0)
  • 2020-12-29 05:25
    Array.prototype.splice.apply( [1,2,3], [2, 0].concat([4,5,6]) );
    
    0 讨论(0)
提交回复
热议问题