问题描述
我正在浏览一些代码,我想知道这是如何有用的
I was browsing through some code and I was wondering how this could be useful
grid.push([].concat(row));
据我所知,它与
grid.push([row]);
为什么'concat'大惊小怪?
Why the 'concat' fuss?
推荐答案
当你需要展平数组并且没有包含其他数组的数组时,你想使用 .concat
。例如,
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];
情景1
console.log(b.push(a));
// Result: [4, [1,2,3]]
场景2
console.log(b.concat(a));
// Result: [4,1,2,3]
所以你们两个都是数组数组中的场景。由于 []。concat()
只导致数组,推送 [row]
, []。concat(row)
具有相同的结果。
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.
但是如果你想要一个扁平数组,你的代码需要稍作改动,你必须 .concat
数组行
, grid
而非 .push
concat的结果,如方案2
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
这篇关于Concat在Javascript中的空数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!