NodeList對象是一個節點的集合,一般是由Node.childNodes和document.querySelectorAll返回的
注意,NodeList對象不是一個數組,因此並沒有數組擁有的一些方法,比如forEach和map等,普通數組的原型鏈是:
myArray --> Array.prototype --> Object.prototype --> null
(想要獲得一個對象的原型鏈,可以連續調用Object.getPrototypeof,直到返回null,即原型鏈的盡頭)
而NodeList的原型鏈是:
myNodeList --> NodeList.prototype --> Object.prototype --> null
如何將NodeList轉換爲Array?
可以通過Array.prototype.slice.call(myNodeList);
例子:
var list = document.querySelectorAll('div');
var array = Array.prototype.slice.call(list);
該方法也可以用來處理參數,例子:
function test(a, b, c, d){ var arg = Array.prototype.slice.call(arguments, 1); alert(arg); }
test(1, 2, 3, 4); //2, 3, 4
其實這樣寫就類似於arguments.slice(1),只是因爲arguments並不是一個數組對象,只是個類數組而已,並沒有slice這個方法,而上述的方法是將arguments轉換成一個數組對象,讓arguments具有slice方法
參考鏈接: