map and forEach, why the third one is invalid
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));
How to output the value of forEach as an array??
習慣沉默2017-05-19 10:28:35
Okay, actually x=>x+x is an abbreviation, which is equivalent to x=>{return x+x;}; return in forEach will terminate the traversal
伊谢尔伦2017-05-19 10:28:35
forEach has no return value and needs to be written in two steps, or use the last method
阿神2017-05-19 10:28:35
If you want this effect, you need to manually create a new array and operate it in forEach
var resultArr = []
arr.forEach((item) => {resultArr.push(item)})
console.log(resultArr)
淡淡烟草味2017-05-19 10:28:35
As the name suggests, for each means "for each operation", and map means "one-to-one matching".
So forEach
will not care about the return value.
It’s pointless to ask why something like this is artificially set, check the API more.