2 回答

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

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);
添加回答
舉報