hh54188
hh54188

Reputation: 15656

Javascript:why the array slice method could turn nodelist or arguments to array?

I know the usage like:

Array.prototype.slice.call(document.querySelectorAll('a')) 

to turn Nodelist datatype to array without a parameter, but I read from the W3CSchool about the usage of slice, the first parameter start is required:

start Required. An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array

so without a parameter and call that method is just OK? Why this could success?

Upvotes: 1

Views: 138

Answers (2)

Paul S.
Paul S.

Reputation: 66404

Let's play a game of follow the breadcrumbs

In the es5 spec,

  1. Array.prototype.slice(start, end)

    Let relativeStart be ToInteger(start)

  2. ToInteger

    1. Let number be the result of calling ToNumber on the input argument

  3. ToNumber

    Undefined transforms to NaN

  4. Backtrack ToInteger

    2. If number is NaN, return +0.

So even though it is not explicitly stated to be optional, if start is undefined, it becomes 0.

Upvotes: 3

go-oleg
go-oleg

Reputation: 19480

Better to use MDN than w3cschools/fools.

Yes, what you are doing is correct, see the "Array-like objects" section of:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Upvotes: 0

Related Questions