Question

Suppose that you run this code:

var a = [];
a[4] = true;

Then your array would look like [undefined, undefined, undefined, undefined, true]

But if you run this code:

var a = [];
a.splice(4, 0, true);

You would get [true] instead of, well, [undefined, undefined, undefined, undefined, true]

When using splice, if the index exceeds the current length of the array it just stops at the last element.

Why is this the intended behavior for splice?

Était-ce utile?

La solution

According to the ECMA docs, the 'start' argument cannot be greater than the length of the array or it is set to the length of the array.

5 - Let relativeStart be ToInteger(start).

6 - If relativeStart is negative, let actualStart be max((len + relativeStart),0); else let actualStart be min(relativeStart, len).

http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.12

As for why exactly: I'm not sure, maybe they thought it would be counterintuitive if the method added items to the array.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top