问题描述
我偶然发现了这个将 DOM NodeList 转换为常规数组的简洁快捷方式,但我必须承认,我并不完全理解它是如何工作的:
I stumbled onto this neat shortcut for converting a DOM NodeList into a regular array, but I must admit, I don't completely understand how it works:
[].slice.call(document.querySelectorAll('a'), 0)
所以它以一个空数组[]
开始,然后slice
用于将call
的结果转换为一个新数组是吗?
So it starts with an empty array []
, then slice
is used to convert the result of call
to a new array yeah?
我不明白的是call
.这如何将 document.querySelectorAll('a')
从 NodeList 转换为常规数组?
The bit I don't understand is the call
. How does that convert document.querySelectorAll('a')
from a NodeList to a regular array?
推荐答案
这里发生的事情是你调用 slice()
就好像它是 NodeList
的函数一样使用call()
.slice()
在这种情况下所做的是创建一个空数组,然后遍历它正在运行的对象(最初是一个数组,现在是一个 NodeList
)并继续追加元素该对象到它创建的空数组,最终返回.这是一篇文章.
What's happening here is that you call slice()
as if it was a function of NodeList
using call()
. What slice()
does in this case is create an empty array, then iterate through the object it's running on (originally an array, now a NodeList
) and keep appending the elements of that object to the empty array it created, which is eventually returned. Here's an article on this.
所以它以一个空数组[]开头,然后用slice将调用结果转换为新数组是吗?
这不对.[].slice
返回一个函数对象.一个函数对象有一个函数call()
,它调用将call()
的第一个参数赋值给this
的函数;换句话说,使函数认为它是从参数(document.querySelectorAll('a')
返回的 NodeList
)而不是从数组调用的.
That's not right. [].slice
returns a function object. A function object has a function call()
which calls the function assigning the first parameter of the call()
to this
; in other words, making the function think that it's being called from the parameter (the NodeList
returned by document.querySelectorAll('a')
) rather than from an array.
这篇关于javascript 中 [].slice.call 的解释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!