简体   繁体   中英

JavaScript Array.prototype.fill: meaning of parameters

The documentation on MDN indicates that the syntax for Array.prototype.fill is:

Array.prototype.fill(value[, start[, end]])

The example

 console.log([1, 2, 3].fill(4, 1, 1)); // [1, 2, 3]

in the documentation and my testing agrees with the commented answer.

However, I can't see how that can be right. The parameters indicate that indexes 1 through 1 should be filled with 4 . Index 1 has the value of 2 , so I should have though that the result should be [1,4,3] .

What is the correct interpretation of the parameters start and end ?

Update

The accepted answer below states that the end index is not inclusive. This was not mentioned on MDN, though it is mentioned for another method ( slice ).

I have taken the liberty of updating the MDN article.

If you read polyfill code, you will see following code:

var k = relativeStart < 0 ?
  Math.max(len + relativeStart, 0) :
  Math.min(relativeStart, len);

// Steps 9-10.
var end = arguments[2];
var relativeEnd = end === undefined ?
  len : end >> 0;

// Step 11.
var final = relativeEnd < 0 ?
  Math.max(len + relativeEnd, 0) :
  Math.min(relativeEnd, len);

// Step 12.
while (k < final) {

As you can see, it says while (k < final) . In your case, both k and final holds same value and hence no mutation is made.


If you change the arguments to not being same, you will see the difference.

 console.log([1, 2, 3].fill(4, 1, 2));


As suggested by skyboyer , same logic is shared in ECMA spec

Also suggested by skyboyer ,

[...].slice(1, 1)

does not do anything. But

[...].splice(1,1)

"...".substr(1, 1)

mutates/ returns value. This is because:

@skyboyer for Array.splice, second argument is not index but count. For String.substr second argument is length and not index again. Hence both work just fine


References:

console.log([1, 2, 3].fill(4, 1, 1));

First argument 4 is value to fill with. Second argument 1 is starting index (where to start from). Third argument 1 is ending index which is exclusive.

So if you do: console.log([1, 2, 3].fill(4, 0, 3));

It will start filling [1,2,3] array starting from index 0 (value 1 ) and overwriting all values up to the index of 2 since we said 3 is exclusive.

So result will be: [4, 4, 4]

In simple words

console.log([1, 2, 3].fill(4, 1, 1));  

second and thid parameters are nothing but the length of the array to be filled that is calculated by subtraction in your case 1-1 is 0 so it will not fill any thing if you want to fill only second one you have to use

console.log([1, 2, 3].fill(4, 1, 2)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM