Reputation: 1476
I've just found a slip in my code while copying an array. I did array.splice(0)
, rather than using slice
. But strangely it still works. This usage isn't compliant with the Array.prototype.splice spec on MDN which states that the deleteCount
(second argument) is mandatory and that it returns
"An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. "
I've run some tests in Chrome and this is what I got
var array = [0, 1, 2, 3];
var spliced = array.splice(0); // [0, 1, 2, 3]
But when I do
var array = [0, 1, 2, 3];
var spliced = array.splice(0, 0); // [] as per the spec
Is this an interesting Chrome feature or is the spec out of date?
Upvotes: 2
Views: 798
Reputation: 816552
According to ECMAScript 5, one could argue arr.splice(0)
and arr.splice(0, 0)
should return the same result, because in step 7, ToInteger(undefined)
is 0
.
- Let actualDeleteCount be
min(max(ToInteger(deleteCount),0), len – actualStart
).
However, it's not clear if it is even valid to call .splice
with a single argument.
ECMAScript 6 has a special case for single arguments (and one for no arguments):
- If the number of actual arguments is 0, then
Let insertCount be 0.
Let actualDeleteCount be 0.- Else if the number of actual arguments is 1, then
Let insertCount be 0.
Let actualDeleteCount be len - actualStart
len
is the length of the array and actualStart
is derived from the first argument. So arr.splice(0)
becomes equivalent to arr.splice(0, arr. length)
, which means Chrome seems to comply to the new spec (intentionally or unintentionally).
On the other hand, arr.splice()
is equivalent to arr.splice(0, 0)
and Chrome returns an empty array as expected.
Upvotes: 4