JavaScript "arguments" -passing a function with other parameters
Function multiply
below is passed a callback function "addOne". Function multiply returns [3,5,7].
Since the callback function addOne is one of the arguments of function multiply, and since the arguments of function mu开发者_如何学运维ltiply are all multiplied by 2, why doesnt the callback function itself (i.e. addOne) get multiplied by 2? In other words, instead of function multiply returning [3,5,7]
, I would have expected it to return [3,5,7, NAN]
since the function is not a number?
Does JavaScript interpreter just somehow know not to multiply it by 2?
function addOne(a) {
return a + 1;
}
function multiply(a,b,c, callback) {
var i, ar = [];
for (i = 0; i < 3; i++) {
ar[i] = callback(arguments[i] * 2);
}
return ar;
}
myarr = multiply(1,2,3, addOne);
myarr;
Because your loop's condition is <3
(hehe) which means it won't subscript the callback (the last element).
You should consider making the callback the first argument always, and splitting the arguments like so...
var argumentsArray = Array.prototype.slice.call(arguments),
callback = argumentsArray.shift();
jsFiddle.
Then, callback
has your callback which you can call with call()
, apply()
or plain ()
, and argumentsArray
has the remainder of your arguments as a proper array.
This line for (i = 0; i < 3; i++) {
is protecting you.
You stop before it hits the callback
argument
Because you are running the the loop for the first 3 args only. i < 3 runs for i=0, i=1,i=2
精彩评论