Why doesn't splice fill holes in javascript array?

Suppose you run this code:

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

Then your array will 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, well, [undefined, undefined, undefined, undefined, true]

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

Why is this the alleged behavior for splicing?

+4
source share
1 answer

According to ECMA docs, the "start" argument cannot be greater than the length of the array or 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); otherwise 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 inconsistent if the method adds elements to the array.

+1
source

Source: https://habr.com/ru/post/1489371/


All Articles