Array.prototype.slice.call(array, 0) 有什么用? [英] What's the use of Array.prototype.slice.call(array, 0)?

查看:45
本文介绍了Array.prototype.slice.call(array, 0) 有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚浏览了 Sizzle 的源代码,发现了这行代码:

I was just browsing Sizzle's source code and I came across this line of code:

array = Array.prototype.slice.call( array, 0 );

我查了一下这个函数是什么,但我得出的结论是,它只是返回数组中从索引 0 开始的所有元素,并将整个元素放入数组中,即它根本没有做任何事情.

I looked up what the function is, but I came to the conclusion that it just returns all elements of the array starting from index 0, and puts the whole into the array, i.e. it doesn't really do anything at all.

那么这行代码有什么用呢?我错过了什么?

What is therefore the use of this line of code? What am I missing?

这是来自 https 的第 863 行://github.com/jquery/sizzle/blob/master/sizzle.js#L863.

推荐答案

DOM 通常返回一个 NodeList 用于大多数操作,例如 getElementsByTagName.

The DOM usually returns a NodeList for most operations like getElementsByTagName.

虽然 NodeList 几乎感觉就像一个数组,但它不是.它有一个像数组一样的 length 属性,以及一个方法 item(index) 来访问给定索引处的对象(也可以通过 [index] 访问) 符号),但这就是相似性结束的地方.

Although a NodeList almost feels like an array, it is not. It has a length property like an array does, and a method item(index) to access an object at the given index (also accessible with the [index] notation), but that's where the similarity ends.

所以为了能够使用美妙的数组方法无需将它们全部重写为 NodeList,上面的行很有用.

So to be able to use the wonderful array methods without rewriting them all for a NodeList, the above line is useful.

将其转换为数组的另一个用途是使列表成为静态.NodeLists 通常是活动的,这意味着如果发生文档更改,NodeList 对象会自动更新.如果返回给您的 jQuery 对象在您眼皮底下不断变化,这可能会导致问题.尝试使用以下 snippet 来测试 NodeLists 的活性.

Another use of converting it to an array is to make the list static. NodeLists are usually live, meaning that if document changes occur, the NodeList object is automatically updated. That could cause problems, if a jQuery object returned to you kept changing right under your nose. Try the following snippet to test the liveness of NodeLists.

var p = document.getElementsByTagName('p');
console.log(p.length); // 2
document.body.appendChild(document.createElement('p'));
// length of p changes as document was modified
console.log(p.length); // 3

这篇关于Array.prototype.slice.call(array, 0) 有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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