Array.prototype.slice.call将NodeList转换为Array
2017-02-27 15:04
369 查看
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
注意,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
相关文章推荐
- Array.prototype.slice.call把其他数据类型转换成数组
- Array.prototype.slice.call()详解及转换数组的方法
- 将函数的实际参数转换成数组的方法,习惯用Array.prototype.slice.call(arguments)
- Array.prototype.slice.call()详解及转换数组的方法
- 【笔记】js Array.prototype.slice.call(arguments) 将函数的参数转换为数组方法的见解
- Array.prototype.slice.call()详解及转换数组的方法
- Array.prototype.slice.call()详解及转换数组的方法
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)简析
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments) (转)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- javascript:Array.slice.call 到Array.prototype.slice.call
- 伪数组转为数组 Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments, 1)
- JS 有趣的应用 : Array.prototype.slice.call(arguments,0)