js判断数据类型的方法
typeof 不能精准的的判断
ypeof 运算符返回一个用来表示表达式的数据类型的字符串。
可能的字符串有:”number”、”string”、”boolean”、”object”、”function” 和 “undefined”。
alert(typeof (123));//typeof(123)返回”number”
alert(typeof (“123″));//typeof(“123″)返回”string”
对于Array,Null等特殊对象使用typeof一律返回object,这正是typeof的局限性。
instanceof
instanceof操作符用来在运行时检测一个对象的类型。JavaScript里的每个对象都有一个协议类型,可以通过__proto__ 属性访问。函数同样有一个协议类型的属性,这是由它们创建的任何对象初始化的__proto__。当创建一个函数时,为协议类型会给定一个唯一的对象。instanceof 用一个对象的协议类型确定它是否是一个类的实例,或者是一个结构函数。它返回一个布尔值,用以确定是否一个对象是一个指定类的实例。
const person= function(type) {
this.type = type;
}
const xiaoming= new person('xiaoming');
document.write(xiaoming instanceof person); //returns true
document.write(dog instanceof Object); //returns true
Object.prototype.toString的方法可以准确的判断数据类型:
Object.prototype.toString.call(console.log) [object function]