我刚刚浏览了 Sizzle 的源代码,我看到了这行代码:
array = Array.prototype.slice.call( array, 0 );
我查了一下这个函数是什么,但我得出的结论是它只是返回数组中从索引 0 开始的所有元素,并将整个元素放入数组中,即它实际上什么都不做。
那么这行代码有什么用呢?我错过了什么?
编辑:这是来自 https://github.com/jquery/sizzle/blob/master/sizzle.js#L863 的第 863 行.
最佳答案
DOM 通常返回 NodeList
对于大多数操作,例如 getElementsByTagName
。
虽然 NodeList
几乎感觉像一个数组,但它不是。它有一个像数组一样的 length
属性,还有一个方法 item(index)
来访问给定索引处的对象(也可以使用 [index]
表示法),但这就是相似性结束的地方。
所以才能用上精彩array methods无需为 NodeList
重写它们,上面的行很有用。
将其转换为数组的另一个用途是使列表成为静态的。 NodeLists 通常是实时的,这意味着如果文档发生更改,NodeList 对象会自动更新。如果返回给您的 jQuery 对象在您的眼皮底下不断变化,这可能会导致问题。尝试以下 snippet测试 NodeList 的 active 。
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
关于javascript - Array.prototype.slice.call(array, 0) 有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5145032/