JavaScript:使用 Reduce 方法将多个数组合并为一个数组

我有以下代码:


const intersection = (arr) => {


  //console.log(arr)


  return arr.reduce((a,e) => a+e, [])


}


const arr1 = [5, 10, 15, 20];

const arr2 = [15, 88, 1, 5, 7];

const arr3 = [1, 10, 15, 5, 20];

console.log(intersection([arr1, arr2, arr3]));

我期待我的代码打印,[5,10,15,2015,88,1,5,71,10,15,5,20]但它正在打印5,10,15,2015,88,1,5,71,10,15,5,20


我究竟做错了什么?


慕尼黑8549860
浏览 1005回答 2
2回答

智慧大石

您正在尝试将数组与+运算符组合在一起。由于数组不支持+运算符,因此它们被强制转换为字符串。您可以使用数组展开或Array.concat()使用Array.reduce()以下方法组合它们:const intersection = arr => arr.reduce((a, e) => [...a, ...e], [])const arr1 = [5, 10, 15, 20];const arr2 = [15, 88, 1, 5, 7];const arr3 = [1, 10, 15, 5, 20];console.log(intersection([arr1, arr2, arr3]));或者你可以使用Array.flat():const intersection = arr => arr.flat();const arr1 = [5, 10, 15, 20];const arr2 = [15, 88, 1, 5, 7];const arr3 = [1, 10, 15, 5, 20];console.log(intersection([arr1, arr2, arr3]));

UYOU

不要+用于添加数组。使用concat来代替:const intersection = arr => arr.reduce((a, e) => a.concat(e), []);const arr1 = [5, 10, 15, 20];const arr2 = [15, 88, 1, 5, 7];const arr3 = [1, 10, 15, 5, 20];console.log(intersection([arr1, arr2, arr3]));.as-console-wrapper { max-height: 100% !important; top: auto; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript