最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use arrow function in forEach? - Stack Overflow

programmeradmin5浏览0评论

I am studying about arrow function in Javascript.
I used forEach in two ways.
The one without arrow is working, but the one with arrow is not working.

Could you please let me know why?

    let ary = [1,2,3,4,5];

    function callback (i) {
        console.log(i);
    }

    // Working
    ary.forEach(callback);

    // Not working
    ary.forEach((i)=>callback);

I am studying about arrow function in Javascript.
I used forEach in two ways.
The one without arrow is working, but the one with arrow is not working.

Could you please let me know why?

    let ary = [1,2,3,4,5];

    function callback (i) {
        console.log(i);
    }

    // Working
    ary.forEach(callback);

    // Not working
    ary.forEach((i)=>callback);
Share Improve this question asked Feb 24, 2019 at 5:42 Tsubasa YamaguchiTsubasa Yamaguchi 1751 gold badge3 silver badges11 bronze badges 1
  • 1 You're passing to forEach a function that returns a function, callback. callback itself is never called. Please see: Arrow functions – Nathan Commented Feb 24, 2019 at 5:47
Add a ment  | 

2 Answers 2

Reset to default 8

In the "non-working" code, you're passing a function that returns a function (callback) to forEach. callback itself is never called.

This would actually call the function, but it is basically the same as directly passing callback directly to forEach as in your first example:

ary.forEach((i) => callback(i));

Please see the documentation for arrow functions.

you can use:

ary.forEach(i=>callback);

But you'd better use arrow function in this way,and there is no need to define function callback

let ary = [1,2,3,4,5];

ary.forEach(i=>{
  console.log(i);
});

Arrow functions like anonymous functions. That's an array function,and i is the param.

i=>{
  console.log(i);
}

You can learn more from there Array Functions

发布评论

评论列表(0)

  1. 暂无评论