文章目录
一、js判断数据类型常用的方法
1.最常见的判断方法:typeof
2.已知对象类型: instanceof
3.对象原型链判断方法: prototype 通用但很繁琐
4.根据对象的构造器constructor进行判断
5.严格运算符: ===
6.jQuery方法: jquery.type()
二、使用方法
1.typeof
typeof返回的类型都是字符串形式
代码如下(示例):
alert(typeof "helloworld") ------------------>"string"
alert(typeof 123) ------------------>"number"
alert(typeof [1,2,3]) ------------------>"object"
alert(typeof new Function()) ------------------>"function"
alert(typeof new Date()) ------------------>"object"
alert(typeof new RegExp()) ------------------>"object"
alert(typeof Symbol()) ------------------>"symbol"
alert(typeof true) ------------------>"true"
alert(typeof null) ------------------>"object"
alert(typeof undefined) ------------------>"undefined"
alert(typeof 'undefined') ------------------>"string"
2.instance of
instanceof 后面一定要是对象类型
代码如下(示例):
[1,2,3] instanceof Array -------->true
new Date() instanceof Date -------->true
new Function() instanceof Function -------->true
new Function() instanceof function -------->false
null instanceof Object -------->false
3.Object.prototype.toString.call()
适用于所有类型的判断检测,注意区分大小写. toString方法,在Object原型上返回数据格式
代码如下(示例):
console.log(Object.prototype.toString.call("123")) -------->[object String]
console.log(Object.prototype.toString.call(123)) -------->[object Number]
console.log(Object.prototype.toString.call(true)) -------->[object Boolean]
console.log(Object.prototype.toString.call([1, 2, 3])) -------->[object Array]
console.log(Object.prototype.toString.call(null)) -------->[object Null]
console.log(Object.prototype.toString.call(undefined)) -------->[object Undefined]
4.根据对象的constructor进行判断
1.null和undefined没有constructor;
2.判断数字时使用(),比如 (123).constructor,如果写成123.constructor会报错
3.constructor在类继承时会出错,因为Object被覆盖掉了,检测结果就不对了
5.jQuery方法: jquery.type()
据说是无敌万能的方法.如果对象是null跟undefined,直接返回"null"和"undefined"
注意:在使用时,一定要引入jquery文件,不然会报错,jQuery is not defined
代码如下(示例):
console.log(jQuery.type(undefined) === "undefined") -------->true
console.log(jQuery.type() === "undefined"); -------->true
console.log(jQuery.type(window.notDefined) === "undefined") -------->true
console.log(jQuery.type(123) === "number") -------->true
console.log(jQuery.type('123') === "string") -------->true
console.log(jQuery.type([]) === "array") -------->true
console.log(jQuery.type(true) === "boolean") -------->true
console.log(jQuery.type(function(){}) === "function") -------->true
6.有局限的判断:严格运算符===
通常 = = = 出现在我们的条件判断中,比如判断一个变量是否为空,变量是否为数据等
代码如下(示例):
三、总结
1、一般变量用typeof,
2、已知对象类型用instanceof,
3、通用方法Object.prototype.toString.call()
4、jQuery项目万能方法jQuery.type()