简体   繁体   English

Javascript:为什么数组切片方法可以将nodelist或参数转换为数组?

[英]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: Nodelist数据类型来排列没有参数,但我从读W3CSchool大约的使用slice ,第一参数start是必需的:

start Required. 开始必需。 An integer that specifies where to start the selection (The first element has an index of 0). 一个整数,指定开始选择的位置(第一个元素的索引为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? 为什么这会成功?

Let's play a game of follow the breadcrumbs 让我们玩一个跟随面包屑的游戏

In the es5 spec, 在es5规范中,

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

    Let relativeStart be ToInteger(start) relativeStart成为ToInteger(start)

  2. ToInteger

    1. Let number be the result of calling ToNumber on the input argument 1.设number是输入参数上调用ToNumber的结果

  3. ToNumber

    Undefined transforms to NaN Undefined转换为NaN

  4. Backtrack ToInteger Backtrack ToInteger

    2. If number is NaN , return +0 . 2.如果numberNaN ,则返回+0

So even though it is not explicitly stated to be optional, if start is undefined , it becomes 0 . 因此,即使未明确声明它是可选的,如果start 未定义 ,则它变为0

Better to use MDN than w3cschools/fools . w3cschools / fools更好地使用MDN

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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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