简体   繁体   中英

apply(): what do square brackets mean with a function in-between?

I've found some piece of code, that seems to be working, but I don't understand one of its aspects.

> [].forEach.apply('javascript', [function(char) {
... console.log(`give me… ${char.toUpperCase()}`);
... }]);
give me a… J
give me a… A
give me a… V
give me a… A
give me a… S
give me a… C
give me a… R
give me a… I
give me a… P
give me a… T

Why do we need the second set of these square brackets here, what do they mean? I've never seen a function to put it there. Thanks.

Function.prototype.apply expects 2 arguments.

  1. The this argument.
  2. An array of arguments to be passed to the function.

So the function is put in an array, because the apply function needs an array of arguments. Basically, your code is passing 1 argument, which is a function.

However, you would replace .apply with .call , and then an array of arguments would not be necessary, you could just add multiple arguments to the .call functions.

[].forEach.call('javascript', function(char) {
  console.log(`give me… ${char.toUpperCase()}`);
});

.apply is mostly useful when you have an existing array of arguments or you don't know how many you will pass, which was trick pre-ES6 syntax.

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