为JavaScript节点列表转换为阵的最快方法? [英] Fastest way to convert JavaScript NodeList to Array?
问题描述
previously回答问题,在这里表示,这是最快的方式:
// NL是一个节点列表
VAR ARR = Array.prototype.slice.call(NL);
在在浏览器上基准我已发现,它是比这个慢的3倍以上:
VAR ARR = [];
对于(VAR I = 0,N; N = NL [I]; ++ I)arr.push(N);
他们都产生相同的输出,但我觉得很难相信,我的第二个版本是最快的方式,特别是因为人说,否则在这里。
这是在我的浏览器(铬6)一个怪癖?或者是有一个更快的方法?
编辑:对于任何人谁在乎,我定居在以下(这似乎是在每一个我测试浏览器速度最快):
// NL是一个节点列表
变种L = []; //将持有节点的数组
对于(VAR I = 0,LL = nl.length;我= 11;!l.push(NL [我++]));
EDIT2:我发现了一个更快的方法
// NL是节点列表
VAR ARR = [];
对于(VAR I = nl.length;我 - ; arr.unshift(NL [I]));
第二项往往是在一些浏览器更快,但主要的一点是,你不得不使用它,因为第一个是不跨浏览器。即使时代他们是,鲍勃迪伦
@kangax ( IE 9 preVIEW 的)
Array.prototype.slice 现在可以转换
某些主机对象(例如节点列表的)
以阵列 - 这是大多数
现代浏览器已经能够做到
相当长一段时间。
块引用>例如:
Array.prototype.slice.call(document.childNodes);
Previously answered questions here said that this was the fastest way:
//nl is a NodeList var arr = Array.prototype.slice.call(nl);
In benchmarking on my browser I have found that it is more than 3 times slower than this:
var arr = []; for(var i = 0, n; n = nl[i]; ++i) arr.push(n);
They both produce the same output, but I find it hard to believe that my second version is the fastest possible way, especially since people have said otherwise here.
Is this a quirk in my browser (Chromium 6)? Or is there a faster way?
EDIT: For anyone who cares, I settled on the following (which seems to be the fastest in every browser that I tested):
//nl is a NodeList var l = []; // Will hold the array of Node's for(var i = 0, ll = nl.length; i != ll; l.push(nl[i++]));
EDIT2: I found an even faster way
// nl is the nodelist var arr = []; for(var i = nl.length; i--; arr.unshift(nl[i]));
解决方案The second one tends to be faster in some browsers, but the main point is that you have to use it because the first one is just not cross-browser. Even though The Times They Are a-Changin'
@kangax (IE 9 preview)
Array.prototype.slice can now convert certain host objects (e.g. NodeList’s) to arrays — something that majority of modern browsers have been able to do for quite a while.
Example:
Array.prototype.slice.call(document.childNodes);
这篇关于为JavaScript节点列表转换为阵的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!