Here is a function from a tutorial:
function add() {
var values = Array.prototype.splice.call(arguments, [1]),
total = 0;
for(var value of values) {
total += value;
}
return total;
}
And the expression Array.prototype.splice.call(arguments, [1])
confuses me.
- Why
1
? - And why with brackets
[1]
?
If we pass 1, it represents start
position in splice()
, so it will skip the first argument we pass to add()
, hence it won't add all arguments...
Is this a mistake in the tutorial?
[1]
would just get coerced to1
withinsplice
. However,apply
would make more sense thancall
(or, of course,call
, but then1
instead of[1]
). And yes, this saves all arguments except the first one invalues
. Honestly,slice
would make more sense here…1
doesn't make sense, right? It should be 0, as I understandcalculate
method which uses the first argument as the operation and forgotten to correct it.