[英]Why calling a function inside another function doesn't work?
var mult = (function(){
var cache = {};
var calculate = function(){
var a = 1;
for(var i = 0, l = arguments.length; i < l; i++){
a = a * arguments[i];
}
return a;
}
return function(){
return calculate(arguments);
}
})();
console.log(mult(1, 2));
Above is my code, I expect the mult function will give me value 2, but instead it outputs NaN. 上面是我的代码,我希望mult函数将给我值2,但改为输出NaN。 I changed the line
calculate(arguments)
to caculate.apply(null, arguments)
and it worked. 我将行
calculate(arguments)
更改为caculate.apply(null, arguments)
,它起作用了。 I don't know why the old code doesn't work? 我不知道为什么旧的代码不起作用? Why do I need to use apply in this case?
在这种情况下为什么需要使用Apply? What does
null
represent here? null
在这里代表什么?
Your calculate
function wants separate arguments, but you passed in an array 1 . 您的
calculate
函数需要单独的参数,但是您传入了数组 1 。 Using .apply
spreads the content of the array for you. 使用
.apply
为您扩展数组的内容。
1 Technically an array-like arguments
object that does not inherit from Array
. 1从技术上讲,不是从
Array
继承的类似数组的arguments
对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.