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。