Using es6 spread to concat multiple arrays

前端 未结 8 1244
伪装坚强ぢ
伪装坚强ぢ 2021-01-31 14:50

We all know you can do:

let arr1 = [1,2,3];
let arr2 = [3,4,5];
let arr3 = [...arr1, ...arr2]; // [1,2,3,3,4,5]

But how do you make this dynami

相关标签:
8条回答
  • 2021-01-31 15:26

    Following solution works for me (spread operator in ES6):

    let array = ['my','solution','works'];
    let newArray = [];
    let newArray2 = [];
    newArray.push(...array); //adding to same array
    newArray2.push([...array]); //adding as child/leaf/sub-array
    console.log(newArray);
    console.log(newArray2);

    0 讨论(0)
  • 2021-01-31 15:31

    You can't do that with spread syntax alone, as spread syntax requires you to know how many arrays you are concatenating in advance. However, you could write the following function:

    function concatN(...arguments) {
        let accumulator = [];
        for(let arg = 0; arg < arguments.length; arg = arg + 1) {
            accumulator = [...accumulator, ...arguments[arg]];
        }
        return accumulator;
    }
    

    It probably won't be very efficient, though (repeated use of spread syntax is O(n²)). Using Array.prototype.concatwould be better. You can just do:

    [].concat(all, of, your, arrays);
    
    0 讨论(0)
提交回复
热议问题