1)定義
數(shù)組是一個特殊對象,與常規(guī)對象的區(qū)別:
1.當由新元素添加到列表中時骚灸,自動更新length
屬性
2設置length屬性期虾,可以截斷數(shù)組
3.從Array.protoype中繼承了方法
4.屬性為'Array'
類數(shù)組是一個擁有l(wèi)ength屬性公你,并且他屬性為非負整
數(shù)的普通對象踊淳,類數(shù)組不能直接調(diào)用數(shù)組方法。
2)區(qū)別
本質(zhì):類數(shù)組是簡單對象陕靠,它的原型關系與數(shù)組不同迂尝。
// 原型關系和原始值轉(zhuǎn)換
let arrayLike = {
length: 10,
};
console.log(arrayLike instanceof Array); // false
console.log(arrayLike.__proto__.constructor === Array); // false
console.log(arrayLike.toString()); // [object Object]
console.log(arrayLike.valueOf()); // {length: 10}
let array = [];
console.log(array instanceof Array); // true
console.log(array.__proto__.constructor === Array); // true
console.log(array.toString()); // ''
console.log(array.valueOf()); // []
3)類數(shù)組轉(zhuǎn)換為數(shù)組。轉(zhuǎn)換方法
1.使用Array.from()
2.使用Array.prototype.slice.call()
3.使用Array.prototype.forEach()進行屬性遍歷并組成新的數(shù)組
剪芥。轉(zhuǎn)換須知
垄开。轉(zhuǎn)換后的數(shù)組長度由length屬性決定。索引不連續(xù)時轉(zhuǎn)換結(jié)果是連續(xù)的税肪,會自動補位溉躲。
榜田。代碼示例
let al1 = {
length: 4,
0: 0,
1: 1,
3: 3,
4: 4,
5: 5,
};
console.log(Array.from(al1)) // [0, 1, undefined, 3]
。②僅考慮0或正整數(shù)的索引
// 代碼示例
let al2 = {
length: 4,
'-1': -1,
'0': 0,
a: 'a',
1: 1
};
console.log(Array.from(al2)); // [0, 1, undefined, undefined]
③使用slice轉(zhuǎn)換產(chǎn)生稀疏數(shù)組
// 代碼示例
let al2 = {
length: 4,
'-1': -1,
'0': 0,
a: 'a',
1: 1
};
console.log(Array.prototype.slice.call(al2)); //[0, 1, empty × 2]
4)使用數(shù)組方法操作類數(shù)組注意地方
let arrayLike2 = {
2: 3,
3: 4,
length: 2,
push: Array.prototype.push
}
// push 操作的是索引值為 length 的位置, 所以下面的2對應1, 之后length變3, push(2) 之后 3對應 2
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: ?}