问题描述
面试被问到这个问题。我想了想,肯定不能用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
9function 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 | object instanceof 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
10Array.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
当判断数组实例的时候,使用isArray
比instanceOf
更可靠。因为它在iframes
也能正常工作。
reference: