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

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

问题描述

我只是浏览灒源$ C ​​$ c和我碰到这条线code的传来:

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.

因此​​,所用这条线code的?我缺少什么?

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

编辑:这是行863从<一个href=\"https://github.com/jquery/sizzle/blob/master/sizzle.js#L863\">https://github.com/jquery/sizzle/blob/master/sizzle.js#L863.

推荐答案

在DOM通常返回 节点列表 的getElementsByTagName 的大部分操作。

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

虽然节点列表几乎感觉像一个数组,事实并非如此。它有一个长度属性像一个数组确实和方法项(指数)在给定的访问对象指数(也与 [指数] 符号访问),但是这其中的相似之处。

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.

因此​​,为了能够使用的美妙阵列的方法,无需重写他们所有一个节点列表,上面的线是非常有用的。

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对象返回给你蒙对你的鼻子底下发生变化。请尝试以下片断测试的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(数组,0)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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