javascript - Why can't forEach in es6 be written like this??
PHP中文网
PHP中文网 2017-05-19 10:26:35
0
5
568

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??

PHP中文网
PHP中文网

认证0级讲师

reply all(5)
習慣沉默

Okay, actually x=>x+x is an abbreviation, which is equivalent to x=>{return x+x;}; return in forEach will terminate the traversal

Peter_Zhu

forEach的返回值是undefined

伊谢尔伦

forEach has no return value and needs to be written in two steps, or use the last method

阿神

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)
淡淡烟草味

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template