将Node List转换为数组(Array)
querySelectorAll
方法返回一个类数组对象称为node list。这些数据结构被称为“类数组”,因为他们看似数组却没有类似map
、foreach
这样的数组方法。这是一个快速、安全、可重用的方法将node list转换为DOM元素的数组:
const nodelist = document.querySelectorAll('div');
const nodelistToArray = Array.apply(null, nodelist);
//之后 ..
nodelistToArray.forEach(...);
nodelistToArray.map(...);
nodelistToArray.slice(...);
//等...
apply
方法可以在指定this
时以数组形式向方法传递参数。MDN规定apply
可以接受类数组对象,恰巧就是querySelectorAll
方法所返回的内容。如果我们不需要指定方法内this
的值时传null
或0
即可。返回的结果即包含所有数组方法的DOM元素数组。
另外你可以使用Array.prototype.slice
结合Function.prototype.call
或Function.prototype.apply
, 将类数组对象当做this
传入:
const nodelist = document.querySelectorAll('div');
const nodelistToArray = Array.prototype.slice.call(nodelist); // or equivalently Array.prototype.slice.apply(nodelist);
//之后 ..
nodelistToArray.forEach(...);
nodelistToArray.map(...);
nodelistToArray.slice(...);
//等...
如果你正在用ES2015你可以使用展开运算符 ...
const nodelist = [...document.querySelectorAll('div')]; // 返回一个真正的数组
//之后 ..
nodelist.forEach(...);
nodelist.map(...);
nodelist.slice(...);
//等...
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW