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
- Array.prototype.slice.call将NodeList转换为Array
- Array.prototype.slice.call
- Array.prototype.slice.call
- Array.prototype.slice.call
- Array.prototype.slice.call
- Array.prototype.slice.call
- 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)
- Array.prototype.slice.call(arguments)
- 一般的单位转换工具类
- foreach循环里进行元素的remove/add操作
- windows系统
- OpenMP并行程序设计之OpenMP使用入门
- Android 混淆 配置 语法 基础
- Array.prototype.slice.call将NodeList转换为Array
- 解放生产力,CSS3帧动画工具
- insert语句返回主键ID
- 2.3函数和数组
- ORB-SLAM2搭建详细过程
- 基于PCL实现点云框选功能
- Junit中常用的注解说明
- 区块链学堂(2):最简单的智能合约
- 我的软件工程课目标