简体   繁体   English

JavaScript中的foreach循环语法

[英]foreach loop syntax in javascript

Consider myArray as an array of objects. 将myArray视为对象数组。

Are these two pieces of code equivalent ? 这两段代码是否相等?

myArray.forEach((item) => {
  return doAnAction(item);
});


myArray.forEach((item) => {
      doAnAction(item);
    });

Is there any of them that is better in terms of syntax? 在语法方面有没有更好的选择? If yes, why ? 如果是,为什么?

The better question is, why you do not use the function directly as callback, like 更好的问题是,为什么不直接将函数用作回调,例如

myArray.forEach(doAnAction);

The callback must follow the API of Array#forEach , which is 回调必须遵循Array#forEach的API,即

Function to execute for each element, taking three arguments: 为每个元素执行的函数,采用三个参数:

  • currentValue : The current element being processed in the array. currentValue :数组中正在处理的当前元素。
  • index : The index of the current element being processed in the array. index :数组中正在处理的当前元素的索引。
  • array : The array that forEach() is being applied to. array :要应用forEach()的数组。

If you need only the element, then you could use the given callback directly without any mapping. 如果只需要元素,则可以直接使用给定的回调而无需任何映射。

As I understand there's no difference between these two because you are providing an anonymous function to be applied to each element in the Array whereas the first one does return the result of doAnAction(item) (which is ignored anyway) and the second one does not. 据我了解,这两者之间没有区别,因为您提供了一个要应用于Array中每个元素的匿名函数,而第一个确实返回doAnAction(item)的结果doAnAction(item)无论如何都会被忽略),而第二个则不返回。

So they are really equivalent, the second just makes more sense to me for the intended meaning. 因此,它们实际上是等效的,对于我而言,第二个对我来说更有意义。

This is not specific to the forEach loop. 这不是特定于forEach循环的。 It is just ES6 syntax. 这只是ES6语法。

With ES5, here is the right syntax: 对于ES5,这是正确的语法:

myArray.forEach(function (item) {
  doAnAction(item);
});

With ES6, you have more possibilities: 使用ES6,您将拥有更多的可能性:

// Solution #1
myArray.forEach((item) => {
  doAnAction(item);
});

// Solution #2
myArray.forEach(item => {
  doAnAction(item);
});

// Solution #3
myArray.forEach(item => doAnAction(item));

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

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