1、定义
数组是一个特殊对象,与常规对象的区别:
当由新元素添加到列表中时,自动更新length属性
设置length属性,可以截断数组
从Array.protoype中继承了方法
属性为'Array'
类数组是一个拥有length属性,并且他属性为非负整数的普通对象,类数组不能直接调用数组方法。
2、区别
本质:类数组是简单对象,它的原型关系与数组不同。
3、类数组转换为数组
转换方法
(1)、使用Array.from()
(2)、使用Array.prototype.slice.call()
(3)、使用Array.prototype.forEach()进行属性遍历并组成新的数组
转换须知
<1>转换后的数组长度由length属性决定。索引不连续时转换结果是连续的,会自动补位。(如果类数组没有索引2,则转化为数组的时候索引2是 undefined )
<2>仅考虑 0或正整数 的索引 (其他的都转化成 undefined )
<3>使用slice转换产生稀疏数组
let al2 = {
length: 4,
'-1': -1,
'0': 0,
a: 'a',
1: 1
};
console.log(Array.prototype.slice.call(al2)); //[0, 1, empty × 2]
使用数组方法操作类数组注意地方
let arrayLike2 = {
2: 3,
3: 4,
length: 2,
push: Array.prototype.push
}
// push 操作的是索引值为 length 的位置
arrayLike2.push(1);
console.log(arrayLike2); // {2: 1, 3: 4, length: 3, push: ƒ}
arrayLike2.push(2);
console.log(arrayLike2); // {2: 1, 3: 2, length: 4, push: ƒ}