es5和es6中如何将类数组转换成真数组的方法?

124 阅读1分钟

类数组转换为真数组

  1. 什么是类数组
一个假的数组,它有下标,有索引作为属性,有length,可以for循环,看起来像一个真数组。
  1. 什么是真数组
原型链上一定要有Array.prototype
  1. 判断是否为真数组的方法
方法1:
使用数组构造函数上的静态方法
Array.isArray(arr) //返回true或false
方法2: 
arr instanceof Array // 返回true或者false
  1. es5中类数组转真数组的方法
Array.prototype.slice.call(类数组)
示例:
var arr=document.querySelectorAll('a')  //获取页面的a标签组成的类数组
onsole.log(arr instanceof NodeList//true
Array.prototype.slice.call(arr)/[].slice.call(arr)
console.log(arr instanceof NodeList)//false
console.log(Array.isArray(arr))//true
[].slice.call(类数组)
  1. es6类数组转真数组的方法
Array.from(类数组)