typeof 可以判断数据的类型 返回值为6个字符串,分别为 string , object , function , number , undefined , Boolean ;但是当数据为array、object、null、new出的实例时,typeof的返回值都是object,得不到真正的数据类型。
而利用Object.prototype.toString.call( )可以很好的解决这个问题。返回值同样为字符串,分别有"[object Number]"、"[object String]"、"[object Boolean]"、"[object Object]"、"[object Function]"、"[object Null]"、"[object Array]"、"[object Undefined]"。可以清晰的分辨出array、null及object 。
还有一个问题,那就是如何判断某个变量是否是某个对象的实例呢?
这时候,就有了instanceof的出现了,其返回值为boolean类型
function Animal(){
this.name = "动物" ;
}
let dog = new Animal() ;
console.log( dog instanceof Animal ) //true
console.log( {} instanceof Animal ) //false
哪里不对还请各位大佬指出,鄙人前端菜鸡一枚。