JavaScript中的數組與類數組/僞數組

1、數組

1. 數組的聲明方式:

let a = []  // 這是使用數組直接量Array Literal建立數組
let b = new Array()  // 這是用構造函數array()建立數組對象複製代碼

因爲JavaScript的內置構造函數都是繼承自Object.prototype,那麼以上兩種方式創造出的數組對象,都會擁有Object.prototype上的屬性值。而Array.prototype又繼承自Object.prototype,因此經過數組直接量建立的數組,既有Array.prototype的屬性值,又有Object.prototype的屬性值。javascript

let a = []   // [object Array]
let b = new Array()  // [object Array]
let c = {}  // [object Object]
let d = new Object() // [object Object]
console.log(Object.prototype.toString.call(a))
console.log(Object.prototype.toString.call(b))
console.log(Object.prototype.toString.call(c))
console.log(Object.prototype.toString.call(d))複製代碼

2. 數組跟對象的區別:

① 數組是有索引的。java

② 數組有長度,對象無長度。數組

2、僞數組

1. 什麼是僞數組

僞數組的定義中:函數

① 擁有length屬性,索引是非負整數。ui

② 不具備數組的方法。spa

實際上僞數組就是一個對象。prototype

let e = {  
    length: 3,  
    "0": 1,  
    "1": 'sss',  
    "2": 'rerer'
}

for (var i = 0; i < e.length; i++) {  
    console.log(e[i]);
}
e instanceof Array  // false
e instanceof Object // true複製代碼

《JavaScript權威指南》上判斷是否爲僞數組的方式:code

function isArrayLike(o) {     
    if (o &&                                // o is not null, undefined, etc. 
        typeof o === 'object' &&            // o is an object 
        isFinite(o.length) &&               // o.length is a finite number 
        o.length >= 0 &&                    // o.length is non-negative 
        o.length===Math.floor(o.length) &&  // o.length is an integer 
        o.length < 4294967296)              // o.length < 2^32 
        return true;                        // Then o is array-like else 
    return false;                       // Otherwise it is not}複製代碼

還有一種方式:對象

Array.isArray(fakeArray) === false; 
Array.isArray(arr) === true;複製代碼

2. 常見的僞數組

① arguments繼承

(function() {  
    console.log(typeof arguments); // 輸出 object,它並非一個數組
}())複製代碼

② 獲取的DOM對象的數組

let f = document.querySelectorAll('a)複製代碼
相關文章
相關標籤/搜索