●[] .slice.call在JavaScript解释? [英] Explanation of [].slice.call in javascript?
问题描述
我偶然到这个整洁的快捷方式用于将DOM节点列表成常规数组,但我必须承认,我不完全理解它是如何工作:
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)
因此,它与空数组开始 []
,那么片
来的结果转换呼叫
来一个新的数组是吗?
So it starts with an empty array []
, then slice
is used to convert the result of call
to a new array yeah?
我不明白该位是呼叫
。你觉得如何转换 document.querySelectorAll('A')
从节点列表到正规的阵列?
The bit I don't understand is the call
. How does that convert document.querySelectorAll('a')
from a NodeList to a regular array?
推荐答案
这里发生的事情是,你叫片()
,就好像它是一个函数<$ C使用调用$ C>节点列表
()。什么片()
确实在这种情况下创建一个空数组,然后通过它的(原本是一个数组运行对象迭代,现在节点列表
),并保留追加该对象的元素,它创建的空数组,这是最终返回。下面是关于这的文章。
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.
编辑:
因此,它与空数组[]开始,然后切片用于
调用的结果转换为一个新的数组是吗?
So it starts with an empty array [], then slice is used to convert the result of call to a new array yeah?
这是不正确的。 []。片
返回一个函数对象。函数对象有一个函数()调用
它调用函数分配通话)
第一个参数(以这个
;换句话说,使得该函数认为它正在从参数(节点列表
按 document.querySelectorAll返回('A')$称为C $ C>),而不是从一个数组。
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.
这篇关于●[] .slice.call在JavaScript解释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!