map與forEach, 為什麼第3個無效
let arr0=[1,2,3,5,0,9,1000,294,85,3850];
console.log(arr0.map(x=>x+x));
arr0.map(x=>console.log(x+x));
console.log(arr0.forEach(x=>x+x)); // ??
arr0.forEach(x=>console.log(x+x));
怎麼才能把forEach的值當作一個陣列輸出呢??
好吧,其實x=>x+x是個簡寫,等價於x=>{return x+x;};forEach裡return會終止遍歷的
forEach
的返回值是undefined
forEach沒有回傳值,需要分兩步驟寫,或用最後一個方法
想要這種效果的話,需要手動新建一個數組,在forEach中操作
顧名思義,for each 就是「對每個操作」的意思,map 就是「一一匹配」的意思。
所以
forEach
不會管回傳值。這種人為設定的東西問為什麼沒意思,多查 API。