Thomson Thomson - 13 days ago 13
Javascript Question

Why ArraySpeciesCreate is called in Array.prototype.splice?

ES6 mentioned

is called in
Array.prototype.splice
in step 12, and the later creates a new array according to is original array. Why
ArraySpeciesCreate
is required to be called to create a copy of the original array? Does
Array.prototype.splice
operate in the original array directly like below?

var a = [1, 2, 3];
a.splice(0, 1); // a is [2, 3] after this statement

Answer

Why ArraySpeciesCreate is required to be called to create a copy of the original array?

It doesn't create a copy of the original array (more below).

Does Array.prototype.splice operate in the original array directly...?

Yes.

splice does two things:

  1. It modifies the array you call it on, and

  2. It creates a new array that contains any entries you remove

ArraySpeciesCreate is used because of #2, so that with a subclassed array, you get back an instance of the subclass:

class CustomArray extends Array {
}

let main = new CustomArray("a", "b", "c", "d");
let deleted = main.splice(1, 2);             // Remove and return b and c
console.log("main", main);                   // ["a", "d"]
console.log("deleted", deleted);             // ["b", "c"]
console.log(deleted instanceof CustomArray); // true

Note how the array we got back from splice is an instance of CustomArray. That's because of the use of ArraySpeciesCreate that you flagged up in your question. From the description of ArraySpeciesCreate in the spec:

The abstract operation ArraySpeciesCreate with arguments originalArray and length is used to specify the creation of a new Array object using a constructor function that is derived from originalArray.

Note that bit at the end. Basically, ArraySpeciesCreate uses the original array's constructor property to build the new array.

Comments