亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Array.reduce() 的回調函數中的 Array.concat()

如何使用 Array.reduce() 的回調函數中的 Array.concat()

慕姐8265434 2022-08-27 09:29:41
//Bonus - uncomment lines 15 and 17const 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 函數的新手,它有點復雜。我正在嘗試扁平嵌套數組,但我真的不知道下一步該怎么做。
查看完整描述

2 回答

?
POPMUISE

TA貢獻1765條經驗 獲得超5個贊

你已經提到了解決方案,你只需要實現它 - 當前項到回調內部的累加器:concatreduce


const 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);


查看完整回答
反對 回復 2022-08-27
?
狐的傳說

TA貢獻1804條經驗 獲得超3個贊

另一個選項 - 平面圖:


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);

查看完整回答
反對 回復 2022-08-27
  • 2 回答
  • 0 關注
  • 125 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號