Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

javascript - 将JavaScript NodeList转换为Array的最快方法?(Fastest way to convert JavaScript NodeList to Array?)

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:(在我的浏览器基准测试中,我发现它比这慢3倍:) 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)?(这是我浏览器中的怪癖(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(EDIT2:我发现了一种更快的方法) // nl is the nodelist var arr = []; for(var i = nl.length; i--; arr.unshift(nl[i]));   ask by jairajs89 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With ES6, we now have a simple way to create an Array from a NodeList: the Array.from() function.(使用ES6,我们现在有一种从NodeList创建数组的简单方法: Array.from()函数。)

// nl is a NodeList let myArray = Array.from(nl)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...