Concat in an empty array in Javascript

后端 未结 4 1214
再見小時候
再見小時候 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:41

    With grid.push([row]); you are pushing an array containing the row itself. If row is an array (e.g. [0, 1, 2]). You will push an array containing another array (i.e. [[0, 1, 2]]).

    With grid.push([].concat(row));, you are pushing an array containing the elements contained in row (i.e. [0, 1, 2]).

    However it is unclear why it is not just written grid.push(row) which, if row is an array, could seem more or less the same as grid.push([].concat(row));.

    I can find two explanations for this:

    1. row is not an array but an "array-like" object and [].concat(row) is used to convert it (just like Array.from could do).

    2. Your coder does not want to push row but a copy of row instead that protected against any further modification of the original row.

提交回复
热议问题