1创建数组
创建数组是基本功,其方法主要包括以下几种:
const arr = [1,2,3] // 数组字面量
const arr = [,,,] // 三元素空位数组(hole array)
const arr = new Array(4) // [,,,,]
const arr = new Array(4,2) // [4,2]
const arr = Array.of(1,2,3) // [1,2,3]
2判断是不是数组
判断是不是数组的方法主要有:
// 方法一
[1,2,3] instanceof Array
// 方法二
[1,2,3].constructor === Array
// 方法三
Object.prototype.toString.call([1,2,3]) === '[object Array]'
// 方法四
Array.isArray([1,2,3])
// 方法五(兼容写法)
function isArray(arr){
return Array.isArray ?
Array.isArray(arr):Object.prototype.toString.call(arr) === '[object Array]'
}
复制代码
一般最常用的应该是 isArray
方法。
3类数组和数组的转换
我们有时碰到的数据结构不是纯数组,一般将其归类为“类数组”,类数组可以借助以下方法转为纯数组:
const x = document.querySelectorAll('a');
// 方法一
Array.prototype.slice.call(x);
// 方法二
Array.from(x);
Array.from(x,mapFn,thisArg);
// 方法三
[...x]
// 方法四
function toArray(x){
let res = []
for(item of x){
res.push(item)
}
return res
}
// 方法五
Array.apply(null,x)
// 方法六
[].concat.apply([],x)
复制代码
方法五和六本质上都是利用了 apply 的特点,即传给 apply 的第二个参数(数组或者类数组)会被转换为一个参数列表,这些参数再送到调用的方法(new Array 或者 concat)中。