简体   繁体   中英

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:

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) ?

Yes there is no need to wrap "someFunc" in an anonymous () => "arrow function"

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).

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

  • the callback should accept exactly one argument or conform to the forEach calling convention 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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