Javascript - insert an array inside another array

前端 未结 10 2154
刺人心
刺人心 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:01

    I wanted to find a way to do this with splice() and no iterating: http://jsfiddle.net/jfriend00/W9n27/.

    a1 = [1,2,3,4,5];
    a2 = [21,22];
    
    a2.unshift(2, 0);          // put first two params to splice onto front of array
    a1.splice.apply(a1, a2);   // pass array as arguments parameter to splice
    console.log(a1);           // [1, 2, 21, 22, 3, 4, 5];
    

    In general purpose function form:

    function arrayInsertAt(destArray, pos, arrayToInsert) {
        var args = [];
        args.push(pos);                           // where to insert
        args.push(0);                             // nothing to remove
        args = args.concat(arrayToInsert);        // add on array to insert
        destArray.splice.apply(destArray, args);  // splice it in
    }
    

提交回复
热议问题