Array.prototype.slice.call将NodeList转换为Array

来源:互联网 发布:苹果mac应用商店 编辑:程序博客网 时间:2024/05/29 19:07

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方法


参考链接:

https://developer.mozilla.org/zh-CN/docs/Web/API/NodeList

0 0
原创粉丝点击