[英]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. Function.prototype.apply
需要2个参数。
this
argument. this
说法。 So the function is put in an array, because the apply
function needs an array of arguments. 因此,该函数放置在数组中,因为apply
函数需要一个参数数组。 Basically, your code is passing 1 argument, which is a function. 基本上,您的代码传递1个参数,它是一个函数。
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. 然而,你将取代.apply
与.call
,然后参数数组就没有必要,只需要添加多个参数的.call
功能。
[].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. 当您有一个现有的参数数组或不知道要传递多少参数时, .apply
很有用,这是ES6之前的语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.