数据类型判断大概有四种 typeof、instanceof、constructor、Object.prototype.toString.call()
比如说检测 num=10 的数据类型
1.Type:
typeof 检测数据类型会返回对应的数据类型小写字符。
引用数据类型中的:Array,Object,Date,RegExp。不可以用 typeof 检测。都会返回小写的 object
console.log(typeof num);
2 . instanceof
除了使用 typeof 来判断,还可以使用 instanceof。instanceof 运算符需要指定一个构造函数,或者说指定一个特定的类型,它用来判断这个构造函数的原型是否在给定对象的原型链上。
console.log(arr instanceof Array);
3.constructor
constructor 是 prototype 对象上的属性,指向构造函数。我们可以用实例的隐式原型去找到构造函数的值。
console.log(num.proto.constructor);
4 . 使用 Object.prototype.toString.call()检测对象类型
可以通过 toString() 来获取每个对象的类型。每个对象都能通过 Object.prototype.toString() 来检测
console.log(Object.prototype.toString.call(num));