javascript中有一些对象看起来用起来像是数组,但是他们并不是数组。比如arguments
和NodeList
对象。为了方便操作,需要将这类数据类型转换为数组类型。下面以NodeList
为例,介绍几种数组转换方法:
slice.call
var div_list = document.querySelectorAll('div'); // returns NodeList
var div_array = Array.prototype.slice.call(div_list); // converts NodeList to Array
spraead operator
var div_list = document.querySelectorAll('div'); // returns NodeList
var div_array = [...div_list]; // converts NodeList to Array
Array.from
var div_list = document.querySelectorAll('div'); // returns NodeList
var div_array = Array.from(div_list); // converts NodeList to Array
遍历
var div_list = document.querySelectorAll('div'); // returns NodeList
Object.keys(div_list).forEach(function(key) {
console.log(div_list[key]);
})