1. 通过typeof来判断数据类型 (注意返回的类型是小写的字符串格式)
typeof 123 --->"number"
typeof '123' ---> 'string'
typeof true ---> 'boolean'
typeof undefined ---> 'undefined'
typeof null ---> 'object'
typeof function() {} ---> 'function'
typeof {} ---> 'object'
typeof [] ---> 'object'
typeof Symbol(1) ---> 'symbol'
2.通过instanceof 来判断数据类型 返回的true 或 false 是boolean类型
123 instanceof Number ---> false
'123' instanceof String ---> false
true instanceof Boolean ---> false
undefined instanceof undefined -->报错
null instanceof null --> 报错
[] instanceof Array ---> true
{} instanceof Object ---> true
function(){} instanceof Function ---> true
- instanceof 实现方法
function myinstanceof(left, right) {
// 先检查左边参数如果是基本数据类型 或者是null 就返回 false
if (typeof left !== "object" || left === null) return false;
// 通过Object.getPrototypeOf(left) 获取参数的原型对象
var proto = Object.getPrototypeOf(left);
while (true) {
//当最后找到最高的原型对象null时,证明类型不相等
if (proto === null) return false;
//当左边对象的原型对象 == 引用数据类型的原型对象时 证明类型相等
if (proto === right.prototype) return true;
//否则继续查找上一层原型对象
proto = Object.getPrototypeOf(proto);
}
}
console.log(myinstanceof({}, Object));
这两者的区别是instanceof 可以准确的判断复杂引用类型的数据,但不能正确判断基础数据类型,typeof 可以准确判断除null的基础数据类型,但不能正确判断引用数据类型。
3.通过Object.prototype.toString().call() 来判断类型(返回字符串类型)
引用数据类型的原型对象上都有toString()的原型方法,除了对象,其余的都被重写了,所以对象可以直接使用Object.prototype.toString() 返回 "[Object Object]"
Object.prototype.toString({}) ---> "[Object Object]"
Object.prototype.toString.call({}) ---> "[Object Object]"
Object.prototype.toString.call([]) ---> "[object Array]"
Object.prototype.toString.call(true) ---> "[Object Boolean]"
Object.prototype.toString.call(null) ---> "[Object Null]"
Object.prototype.toString.call(undefined) ---> "[Object Undefined]"
Object.prototype.toString.call(function(){}) ---> "[Object Function]"
Object.prototype.toString.call("122") ---> "[Object String]"
Object.prototype.toString.call(123) ---> "[Object Number]"
Object.prototype.toString.call(Symbol(1)) ---> "[Object Symbol]"
Object.prototype.toString.call(document) ---> "[Object HTMLDocument]"
Object.prototype.toString.call(window) ---> "[Object Window]"
4.通过以上几种方式,整合一种通用判断类型方法
function getType(value) {
//普通数据类型由typeof 来判断
if (typeof value !== "object") return typeof value;
var type = Object.prototype.toString.call(value);
return type.slice(8, type.length - 1).toLowerCase();
}