- object.prototype.toString.call(value)
使用Object.prototype上的原生toString()方法判断数据类型,使用方法如下:
Object.prototype.toString.call(value)1.判断基本类型:
Object.prototype.toString.call(null);//"[object Null]" Object.prototype.toString.call(undefined);//"[object Undefined]" Object.prototype.toString.call(“abc”);//"[object String]" Object.prototype.toString.call(123);//"[object Number]" Object.prototype.toString.call(true);//"[object Boolean]"复制代码
2.判断原生引用类型:
函数类型Function fn(){console.log(“test”);} Object.prototype.toString.call(fn);//"[object Function]"复制代码
日期类型var date = new Date(); Object.prototype.toString.call(date);//"[object Date]"复制代码
数组类型var arr = [1,2,3]; Object.prototype.toString.call(arr);//"[object Array]"复制代码
正则表达式var reg = /[hbc]at/gi; Object.prototype.toString.call(reg);//"[object RegExp]"复制代码
自定义类型function Person(name, age) { this.name = name; this.age = age; } var person = new Person("Rose", 18); Object.prototype.toString.call(person); //"[object Object]"复制代码
很明显这种方法不能准确判断person是Person类的实例,而只能用instanceof 操作符来进行判断,如下所示:console.log(person instanceof Person);//输出结果为true复制代码
3.判断原生JSON对象:
var isNativeJSON = window.JSON && Object.prototype.toString.call(JSON); console.log(isNativeJSON);//输出结果为"[object JSON]"说明JSON是原生的,否则不是;复制代码
注意:Object.prototype.toString()本身是允许被修改的,而我们目前所讨论的关于Object.prototype.toString()这个方法的应用都是假设toString()方法未被修改为前提的。
- typeof
typeof通常用来判断基本数据类型。当判断对象,数组和null时都返回object. typeof 'asd' =>"string" typeof 123 =>"number" typeof true =>"boolean" typeof undefined =>"undefined" typeof NaN =>"number" typeof null =>"object" typeof [1,2,3] =>"object" typeof {a: '1'} =>"object" function a(){} typeof a =>"function" 复制代码
3.instanceof
instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性,意思就是该变量通过原型链上能否找到构造函数的prototype 属性
var arr = [1,2,3]
var obj = {a: '1'}
arr instanceof Array =>true
arr instanceof Object =>true //数组也是对象
obj instanceof Object =>true复制代码
4.constructor
var arr1 = [1,2,3]
var obj={a: '1'}
var s = '123'
var n = 123
arr1.constructor==Array
=>true
arr1.constructor==Object
=>false
obj.constructor==Object
=>true
s.constructor==String
=>true
n.constructor==Number
=>true
true.constructor==Boolean
=>true复制代码
总结:判断基本类型我会用typeof,判断引用类型我会用instanceof,更推荐用Object.prototype.toString.call(value)
未完待续.....