The commonly used method to distinguish data types is typeof, but the result of the typeof method is object for arrays and objects, so we generally use the following four methods to distinguish:
instanceof method
[] instanceof Array;//true
var obj = {};
obj instanceof Array;//false
// 注意:数组也是继承的Object
Array instanceof Object // true
constructor property
[].constructor;//Array(){}
var obj = {};
obj.constructor;//Object(){}
es5 new isArray method
Array.isArray([]);//true
Array.isArray({});//false
toString method
Object.prototype.toString.call([]);//"[object Array]"
Object.prototype.toString.call({});//"[object Object]"
During the interview, you may ask how to write an instanceof method by hand. The code is as follows:
// instanceof方法可以检测 前者是否继承了后者的原型对象 是否可以获得后者原型对象的属性和方法
function myInstanceOf(l, r) {
while (1) {
if (l.__proto__ === r.prototype) {
return true
}
if (l.__proto__ == null) {
return false
}
l = l.__proto__
}
}