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;
}
SOURCE
And the expression Array.prototype.splice.call(arguments, [1])
confuses me.
1
? [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?
Yes this example is mistaken, if you try the code it doesn't work (it ignores the first parameter) exactly as you said. The code would make sense if that line was:
var values = Array.prototype.slice.call(arguments),
Or
var values = Array.prototype.splice.call(arguments, 0),
My guess: the example was made by simplyfing code of another function which had one special parameter and used apply
instead of call
in ES5 syntax.
In the further part of the tutorial, calculating functions are discussed, whose first argument determines the type of calculations to be performed. If you write them in the ES5 syntax, you'd have to delete the first argument. That explains Why 1 - to delete the first argument. Now, why brackets: there are two nearly identical functions in JS: call
and apply
. See this note about apply
:
While the syntax of this function is almost identical to that of call(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.
I think the author of calculation function mistakenly used the syntax for apply
and hence the brackets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With