2021-3-17 類數(shù)組和數(shù)組的區(qū)別,dom的類數(shù)組如何轉(zhuǎn)換成數(shù)組

1)定義

數(shù)組是一個特殊對象,與常規(guī)對象的區(qū)別:
1.當(dāng)由新元素添加到列表中時,自動更新length
屬性
2設(shè)置length屬性,可以截?cái)鄶?shù)組
3.從Array.protoype中繼承了方法
4.屬性為'Array'
類數(shù)組是一個擁有l(wèi)ength屬性,并且他屬性為非負(fù)整
數(shù)的普通對象,類數(shù)組不能直接調(diào)用數(shù)組方法。

2)區(qū)別

本質(zhì):類數(shù)組是簡單對象,它的原型關(guān)系與數(shù)組不同。

// 原型關(guān)系和原始值轉(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()進(jìn)行屬性遍歷并組成新的數(shù)組
。轉(zhuǎn)換須知
。轉(zhuǎn)換后的數(shù)組長度由length屬性決定。索引不連續(xù)時轉(zhuǎn)換結(jié)果是連續(xù)的,會自動補(bǔ)位。
。代碼示例

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對應(yīng)1,  之后length變3, push(2) 之后 3對應(yīng) 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: ?}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容