search

Home  >  Q&A  >  body text

javascript - Why can't forEach in es6 be written like this??

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中文网2836 days ago499

reply all(5)I'll reply

  • 習慣沉默

    習慣沉默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

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-19 10:28:35

    forEach的返回值是undefined

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-19 10:28:35

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

    reply
    0
  • 阿神

    阿神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)

    reply
    0
  • 淡淡烟草味

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

    reply
    0
  • Cancelreply