[英]How does apply function work to read all array arguments passed to inner function?
below i quote from eloquentJavascript 下面我引用eloquentJavascript
function noisy(f) {
return function(arg) {
console.log("calling with", arg);
var val = f(arg);
console.log("called with", arg, "- got", val);
return val;
};
}
the above works for single argument and i got that part clear but what i would like to know is the phrase that comes after regarding apply
method...it says we can pass an array-like argument list to the above function.... i tried doing it and failed... can anyone illustrate how to pass an array-like object of arguments and the function calling the arguments passed? 以上适用于单个参数,我明白了这一部分,但我想知道的是关于
apply
方法之后的短语...它说我们可以将类似数组的参数列表传递给上述函数....我尝试这样做并失败了...有人能说明如何传递类似数组的参数对象以及调用所传递参数的函数吗?
i saw the call, apply and bind functions from other sites but i would like to stick on this tutorial and see how it works here? 我看到了来自其他站点的调用,应用和绑定功能,但我想坚持学习本教程,并了解它在这里的工作原理?
i run the above function as: 我将上述功能运行为:
return noisy(String)(0); //works
return noisy(String).apply(null,[0,1,2,3,4]);
gets the same result as above: 得到与上面相同的结果:
calling with 0 called with 0 - got 0
how can i use apply to the noisy function to read all arguments? 我如何使用适用于嘈杂的功能来读取所有参数?
See the bellow snippet 参见波纹管片段
// Code goes here function noisy(f) { return function() { var args = Array.prototype.slice.call(arguments); for(var i=0;i<args.length;i++){ console.log("calling with", args[i]); var val = f(args[i]); console.log("called with", args[i], "- got", val); } }; } noisy(String)(0); //works noisy(String).apply(null,[0,1,2,3,4]);
You have to use the arguments
object or the ES6 spread operator . 您必须使用
arguments
对象或ES6传播运算符 。
The second operator of apply
expects an array, but it does not apply the array to your function. apply
的第二个运算符期望一个数组,但不会将该数组应用于您的函数。 Instead it will call it by adding every array item as a parameter. 相反,它将通过添加每个数组项作为参数来调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.