Javascript - insert an array inside another array

前端 未结 10 2136
刺人心
刺人心 2020-12-04 09:23

What is the more efficient way to insert an array inside another array.

a1 = [1,2,3,4,5];
a2 = [21,22];

newArray - a1.insertAt(2,a2) -> [1,2, 21,22, 3,4         


        
相关标签:
10条回答
  • 2020-12-04 10:07

    If you want to insert another array into an array without creating a new one, the easiest way is to use either push or unshift with apply

    Eg:

    a1 = [1,2,3,4,5];
    a2 = [21,22];
    
    // Insert a1 at beginning of a2
    a2.unshift.apply(a2,a1);
    // Insert a1 at end of a2
    a2.push.apply(a2,a1);
    

    This works because both push and unshift take a variable number of arguments. A bonus, you can easily choose which end to attach the array from!

    0 讨论(0)
  • 2020-12-04 10:09

    You can now do this if using ES2015 or later:

    var a1 = [1,2,3,4,5];
    var a2 = [21,22];
    a1.splice(2, 0, ...a2);
    console.log(a1) // => [1,2,21,22,3,4,5]
    

    Refer to this for documenation on the spread (...) operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

    0 讨论(0)
  • 2020-12-04 10:11

    The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

    a2 = [21,22];
    a1 = [1,2,...a2,3,4,5];//...a2 is use of spread operator
    console.log(a1);

    0 讨论(0)
  • 2020-12-04 10:11
    var a1 = [1,2,3,4,5];
    var a2 = [21,22];
    
    function injectAt(d, a1, a2) {
        for(var i=a1.length-1; i>=d; i--) {
            a1[i + a2.length] = a1[i];
        }
        for(var i=0; i<a2.length; i++) {
            a1[i+d] = a2[i];
        }
    }
    
    injectAt(2, a1, a2);
    
    alert(a1);
    
    0 讨论(0)
提交回复
热议问题