使用 forEach 展平数组

Flatten an array with forEach

查看 this post 扁平化数组后,我注意到没有人使用过数组方法 forEach。我试了一下但失败了,只收到一个空数组:

let arrays = [[1, 2, 3], [4, 5], [6]];
let result = [];

arrays.forEach( (element) => {
    result.concat(element)
})

console.log(result) //[]

我哪里错了?

你必须result = result.concat(element)

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

let arrays = [[1, 2, 3], [4, 5], [6]];
let result = [];

arrays.forEach((element) => {
  result = result.concat(element)
})

console.log(result) //[]

文档:concat

.concat() 总是 returns 一个新数组。它不会修改它正在运行的数组。

您假设 .concat() 将在完成运算后将结果保存在其操作数中。然而事实并非如此。您需要在 .concat():

之后显式保存结果
result = result.concat(element);

演示:

let arrays = [[1, 2, 3], [4, 5], [6]];
let result = [];

arrays.forEach((element) => {
  result = result.concat(element)
});

console.log(result);

您也可以使用 spread syntax 而不是 .forEach() 来展平数组。

let result = [].concat(...arrays);

演示:

let arrays = [[1, 2, 3], [4, 5], [6]];
let result = [].concat(...arrays);

console.log(result);

concat returns 一个新数组,因此您需要将其分配给 result = result.concat(element)

这样的结果

let arrays = [[1, 2, 3], [4, 5], [6]];
let result = [];

arrays.forEach( (element) => {
    result = result.concat(element)
})

console.log(result)