JavaScript中的数组与类数组/伪数组

2,317 阅读1分钟

一、数组

1. 数组的声明方式:

let a = []  // 这是使用数组直接量Array Literal创建数组
let b = new Array()  // 这是用构造函数array()创建数组对象

由于JavaScript的内置构造函数都是继承自Object.prototype,那么以上两种方式创造出的数组对象,都会拥有Object.prototype上的属性值。而Array.prototype又继承自Object.prototype,所以通过数组直接量创建的数组,既有Array.prototype的属性值,又有Object.prototype的属性值。

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. 数组跟对象的区别:

① 数组是有索引的。

② 数组有长度,对象无长度。

二、伪数组

1. 什么是伪数组

伪数组的定义中:

① 拥有length属性,索引是非负整数。

② 不具有数组的方法。

实际上伪数组就是一个对象。

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权威指南》上判断是否为伪数组的方式:

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)