判断未知变量是否为数组

问题描述

面试被问到这个问题。我想了想,肯定不能用typeof,因为数组也是对象的一种,typeof返回的是object,达不到预期。

解决办法

instanceof

The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.

举个例子:

1
2
3
4
5
6
7
8
9
function Worker(name, position, department){
this.name=name;
this.position=position;
this.department=department;
}
var june = new Worker('june','frontend developer','BI');

june instanceof Worker; //true
june instanceof Object; //true

语法

1
2
3
object instanceof constructor
// object 是要检测的对象
// constructor 检测对象的方法

描述

instanceof用于检测constructor.prototype是否存在于对象的原型链上。

注意

Note that the value of an instanceof test can change based on changes to the prototype property of constructors, and it can also be changed by changing an object prototype using Object.setPrototypeOf. It is also possible using the non-standard proto pseudo-property.

Array.isArray()

判断传入的值是否数组,是返回true,否返回false

1
2
3
4
5
6
7
8
9
10
Array.isArray([]); // true
Array.isArray({name:'june'}); // false
Array.isArray('june'); // false
Array.isArray(9999); // false
Array.isArray(undefined); // false
Array.isArray(null); // false

Array.isArray(new Array()); // true
//很少人知道,Array.prototype 自身也是一个array
Array.isArray(Array.prototype); // true

instanceof vs isArray

当判断数组实例的时候,使用isArrayinstanceOf更可靠。因为它在iframes也能正常工作。

reference: