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))复制代码
① 数组是有索引的。java
② 数组有长度,对象无长度。数组
伪数组的定义中:函数
① 拥有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;复制代码
① arguments继承
(function() {
console.log(typeof arguments); // 输出 object,它并非一个数组
}())复制代码
② 获取的DOM对象的数组
let f = document.querySelectorAll('a)复制代码