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. I changed the line calculate(arguments) to caculate.apply(null, arguments) and it worked. I don't know why the old code doesn't work? Why do I need to use apply in this case? What does null represent here?
1 Answer 1
Your calculate function wants separate arguments, but you passed in an array 1. Using .apply spreads the content of the array for you.
1 Technically an array-like arguments object that does not inherit from Array.
answered Jan 4, 2018 at 22:21
Derek 朕會功夫
94.8k45 gold badges199 silver badges255 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
Paul
Well, technically he passed in the array-like
arguments object, but close enough. ;)Derek 朕會功夫
You are absolutely correct, but using the word "array" is easier to understand than "array-like
arguments object" :)Paul
I know, I just wanted to be pedantic to pre-empt follow up questions about why certain array functions weren't working.
CacaJ
but why did it use apply.(null..)? what does null represent?
|
lang-js
return calculate(...arguments);