Concat in an empty array in Javascript

后端 未结 4 1178
再見小時候
再見小時候 2021-02-20 08:24

I was browsing through some code and I was wondering how this could be useful

grid.push([].concat(row));

In my understanding it is the same as<

4条回答
  •  难免孤独
    2021-02-20 08:37

    You want to use .concat when you need to flatten the array and not have an array consisting of other arrays. E.g.

    var a = [1,2,3];
    var b = [4];
    

    Scenario 1

    console.log(b.push(a));
    // Result: [4, [1,2,3]]
    

    Scenario 2

    console.log(b.concat(a));
    // Result: [4,1,2,3]
    

    So both of your scenarios in an array of array. Since [].concat() results in an array only, pushing both [row], [].concat(row) has the same result.

    But if you want a flattened array, there is a slight change needed in your code, that you have to .concat the array row with grid and not .push the result of concat to it, as shown in scenario 2

提交回复
热议问题