如何使用 Array.reduce() 的回调函数中的 Array.concat()

//Bonus - uncomment lines 15 and 17

const arrays = [["how", "now"], ["brown", "cow"]];

const flattenedArray = arrays.reduce((a,c) => a + c);

// The below line should console.log: ["how", "now", "brown", "cow"]

console.log(flattenedArray);


我是使用 reduce 函数的新手,它有点复杂。


我正在尝试扁平嵌套数组,但我真的不知道下一步该怎么做。


慕姐8265434
浏览 99回答 2
2回答

POPMUISE

你已经提到了解决方案,你只需要实现它 - 当前项到回调内部的累加器:concatreduceconst arrays = [["how", "now"], ["brown", "cow"]];const flattenedArray = arrays.reduce((a,c) => a.concat(c));console.log(flattenedArray);但会容易得多:.flat()const arrays = [["how", "now"], ["brown", "cow"]];const flattenedArray = arrays.flat();console.log(flattenedArray);

狐的传说

另一个选项 - 平面图:const arrays = [["how", "now"], ["brown", "cow"]];const flattenedArray = arrays.flatMap(a => a);console.log(flattenedArray);但是,只有当你想在地图中做一些事情时,它才是真正有利的,就像这样:const arrays = [["how", "now"], ["brown", "cow"]];const flattenedArray = arrays.flatMap(a => a.concat(a));console.log(flattenedArray);或者像这样:const arrays = [["how", "now"], ["brown", "cow"]];const flattenedArray = arrays.flatMap(a => a.map(b => b.toUpperCase()));console.log(flattenedArray);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript