将嵌套数组的元素合并到一个大数组中

Merging the elements of nested arrays into one big array

本文关键字:数组 一个 嵌套 元素 合并      更新时间:2023-09-26

我正在尝试将数组的元素合并到一个大数组中。但是我收到一条消息说:

ReferenceError: reduce is not defined

这是我的代码:

var arrays = [[1, 2, 3], [4, 5], [6]];
console.log(reduce(arrays, function(arrayOne, arrayTwo){
    return arrayOne.concat(arrayTwo);
}, 0));

reduce()Array对象的方法,因此必须使用arrays.reduce()

此外,由于您的初始值设置为 0(第二个参数),因此您不能对其使用 arrayOne.concat,因为它不是数组,因此您必须将初始值设置为 []

var arrays = [[1, 2, 3], [4, 5], [6]];
console.log(arrays.reduce(function(arrayOne, arrayTwo){
    return arrayOne.concat(arrayTwo);
}, []));

请注意,调用Array.flat更容易:

var arrays = [[1, 2, 3], [4, 5], [6]];
// If you expect a multi-level nested array, you should increase the depth.
var depth = 1;
console.log(arrays.flat(depth));

reduce() 只在数组上定义,你不能单独调用它:

arrays.reduce(
   function (a, b) { return a.concat(b); }
);
// Array [ 1, 2, 3, 4, 5, 6 ]