JavaScript中 判断数组的几种方法详解

360 阅读2分钟

「这是我参与11月更文挑战的第24天,活动详情查看:2021最后一次更文挑战

前言

在 JavaScript 中,数组是属于 Object 类型的,也就是属于引用类型。

引用类型存放在堆内存中,在栈内存会有一个或者多个地址来指向这个堆内存。

所以对于引用类型,我们不能 typeof 来判断具体的类型,因为返回的都是 Object 。

1. instanceof 操作符判断

用法:arr instanceof Array

instanceof 主要是用来判断某个实例是否属于某个对象

let arr = [];
console.log(arr instanceof Array); // true

注意:

prototype 属性是可以修改的,并不是最初判断为 true 就一定永远为真。

其次,当脚本拥有多个全局环境,例如:html 中拥有多个 iframe 对象,instanceof 的验证结果可能不会符合预期。

// 为 body 创建并添加一个iframe对象
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
// 取得 iframe 对象的构造数组方法
xArray = window.frames[0].Array;
// 通过构造函数获取一个实例
var arr = new xArray(1,2,3); 
console.log(arr instanceof Array); // false  

导致这种问题是因为 iframe 会产生新的全局环境,它也会拥有自己的 Array.prototype 属性,让不同环境下的属性相同很明显是不安全的做法,所以 Array.prototype !== window.frames[0].Array.prototype,想要 arr instanceof Array 为 true,得保证 arr 是由原始 Array 构造函数创建时才可行。

2. 对象构造函数的 constructor 判断

用法:arr.constructor === Array

Object 的每个实例都有构造函数 constructor,用于保存着用于创建当前对象的函数

let arr = [];
console.log(arr.constructor === Array); // true

3. Array 原型链上的 isPrototypeOf

用法:Array.prototype.isPrototypeOf(arr)

Array.prototype 属性表示 Array 构造函数的原型。其中有一个方法是 isPrototypeOf() 用于测试一个对象是否存在于另一个对象的原型链上。

let arr = [];
console.log(Array.prototype.isPrototypeOf(arr)); // true

4. Object.getPrototypeOf

用法:Object.getPrototypeOf(arr) === Array.prototype Object.getPrototypeOf() 方法返回指定对象的原型

let arr = [];
console.log(Object.getPrototypeOf(arr) === Array.prototype); // true

5. Object.prototype.toString

用法:Object.prototype.toString.call(arr) === '[object Array]'

虽然 Array 也继承自 Object,但 js 在 Array.prototype 上重写了 toString,而我们通过 toString.call(arr) 实际上是通过原型链调用了

let arr = [];
console.log(Object.prototype.toString.call(arr) === '[object Array]'); // true

6. Array.isArray(推荐)

用法:Array.isArray(arr)

ES6 中新增了 Array.isArray 方法,IE8 及以下不支持

let arr = [];
console.log(Array.isArray(arr)); // true