简体   繁体   English

如何在forEach中使用箭头功能?

[英]How to use arrow function in forEach?

I am studying about arrow function in Javascript. 我正在研究Javascript中的箭头功能。
I used forEach in two ways. 我以两种方式使用forEach。
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);

In the "non-working" code, you're passing a function that returns a function ( callback ) to forEach. 在“无效”代码中,您正在传递一个函数,该函数一个函数( callback返回给forEach。 callback itself is never called. callback本身从未被调用。

This would actually call the function, but it is basically the same as directly passing callback directly to forEach as in your first example: 这实际上将调用该函数,但是与第一个示例中的直接将回调直接直接传递给forEach基本上相同:

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 但是,您最好以这种方式使用箭头函数,并且无需定义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就是参数。

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

You can learn more from there Array Functions 您可以从那里了解更多阵列功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM