●[] .slice.call在JavaScript解释? [英] Explanation of [].slice.call in javascript?

查看:184
本文介绍了●[] .slice.call在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')),而不是从一个数组。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆