作者:姚一豪
时间:2020-8-20
类数组对象
在页面html中用js获取DOM集合是一个类数组对象:
我们先在body中写三个button
<button>1</button>
<button>2</button>
<button>3</button>
document.querySelectorAll('button')
控制台输出内容`
NodeList(3)
0: <button>
1: <button>
2: <button>
length: 3
<prototype>: NodeListPrototype { item: item(), keys: keys(), values: values(), … }
可以看出我们用querySelectorAll获取的元素是一个类数组集合,不能用数组方法forEach,map等方法,所以将其转换成数组对象是很方便之后的调用
这里我汇总了6个方法将其转换
方法一 Array.prototype.slice.call(arguments)
JavaScript中的Array.prototype.slice.call(arguments)能将有length属性的对象转换为数组(特别注意: 这个对象一定要有length属性).
而document.querySelectorAll(‘button’)的length可以在控制台看出是3,所以让他作为方法参数
Array.prototype.slice.call(document.querySelectorAll('button')).forEach((item) => console.log(item))
```//控制台输出
<button>
<button>
<button>