简体   繁体   English

是否有用于在 JavaScript 列表的每个元素上调用函数的语法糖?

[英]Is there syntactic sugar for calling a function on each element of a list in JavaScript?

Let's say I had the following code:假设我有以下代码:

let array = [1, 2, 3]
array.forEach(x => someFunc(x))

In Java, I know the second line could be simpler using Stream s (at least for static methods), like so:在 Java 中,我知道第二行可以使用Stream更简单(至少对于静态方法),如下所示:

array.stream().map(ClassName::someFunc) ...

Essentially I'm asking is there an analog for the ClassName::someFunc part in JavaScript, instead of having to write x => someFunc(x) ?本质上,我问的是 JavaScript 中的ClassName::someFunc部分是否有模拟,而不必编写x => someFunc(x)

Yes there is no need to wrap "someFunc" in an anonymous () => "arrow function"是的,不需要将“someFunc”包装在匿名() => “箭头函数”中

As long as someFunc's first argument is configured to accept the currently iterated item from the array and do something with it then you can pass in a reference to that function as the argument in .forEach (but do not call it).只要 someFunc 的第一个参数配置为从数组中接受当前迭代的项目并对其进行处理,那么您就可以传入对该函数的引用作为.forEach中的参数(但不要调用它)。

So you would do:所以你会这样做:

let array = [1, 2, 3]
array.forEach(someFunc)

Make sure not to do this:确保不要这样做:

let array = [1, 2, 3]
array.forEach(someFunc())

(note the calling parenthesis, this is bad) (注意调用括号,这很糟糕)

In the simplest case, you can replace在最简单的情况下,您可以替换

array.forEach(x => someFunc(x))

with just只需

array.forEach(someFunc)

but there's some fine print you should be aware of:但是您应该注意一些细则:

  • this generally doesn't work with object methods: .forEach(someObj.someMeth) won't work这通常不适用于对象方法: .forEach(someObj.someMeth)不起作用

  • the callback should accept exactly one argument or conform to the forEach calling convention callback(element, index, this) .回调应该只接受一个参数或符合forEach调用约定callback(element, index, this) For example, array.map(parseInt) won't work either, because parseInt has its own idea of what the second argument means.例如, array.map(parseInt)也不起作用,因为parseInt对第二个参数的含义有自己的想法。

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

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