它如何document.querySelectorAll('a')从a
转换NodeList 为常规数组?
这是我们拥有的代码,
[].slice.call(document.querySelectorAll('a'), 0)
我们先拆一下
[] // Array object
.slice // Accessing the function 'slice' present in the prototype of Array
.call // Accessing the function 'call' present in the prototype of function object(slice)
(document.querySelectorAll('a'),0)
// 'call' can have arguments like, (thisArg, arg1,arg2...n).
// So here we are passing the 'thisArg' as an array like object,
// that is a 'nodeList'. It will be served as 'this' object inside of slice function.
// And finally setting 'start' argument of slice as '0' and leaving the 'end'
// argument as 'undefined'
步骤:1执行call功能
- 在内
call,除以外的thisArg其他参数将附加到参数列表中。
- 现在,该函数
slice将通过将其this值绑定为
thisArg(像来自对象的数组之类document.querySelector)并与参数列表绑定来调用。即]参数start包含0
步骤:2 slice在内部执行的函数的执行call
PS为了更好地理解我们的场景,从调用和切片的原始算法中忽略了一些上下文所需的步骤。
Array.prototype.slice.call(document.querySelectorAll('a'));是编写您编写的代码块的正确方法。