检测变量类型之typeof,instanceof,Object.prototype.toString
2017-09-07 14:04
597 查看
在JS中有时候是需要对一个变量进行检测的,检测到这个变量是什么类型之后,我们就可以做相应的处理。
方法一typeof
typeof方法主要用于基本类型的检测,在检测Boolean,number,undefined,string的时候非常好用。比如:
1 var test1= 1; 2 alert(typeof test1);//输出number 3 var test2 = ""; 4 alert(typeof test2);//输出string 5 var test3 = undefined; 6 alert(typeof test3);//输出undefined 7 var test4 = true; 8 alert(typeof test4);//输出boolean
但是用typeof来检测引用类型的时候就没有那么好用了。因为无论你怎么检测,输出都是object类型。这个时候就要用到Object.prototype.toString方法或者instancof。
方法二instanceof
var test1 = new Array(); alert(test1 instanceof Array);//输出true var test2 = new String(); alert(test2 instanceof String);//输出true var test3 = {}; alert(test3 instanceof Object);//输出true var test4 = /qwe/; alert(test4 instanceof RegExp);//输出true var test5 = 1; alert(test5 instanceof number);//输出false var test6 = ""; alert(test6 instanceof String);//输出false var test7 = true; alert(test7 instanceof Boolean);//输出false
instanceof方法对于引用类型很好用,能彻底检测出是什么类型的引用,但是类似于typeof,instanceof对于基本类型就不好用了,结果都会输出false。
方法三Object.prototype.toString.call
这个方法就是基于上面两个方法的取其精华,去其糟粕而生成的。
var test1 = new Array(); alert(Object.prototype.toString.call(test1));//输出object Array var test2 = new String(); alert(Object.prototype.toString.call(test2));//输出object String var test3 = {}; alert(Object.prototype.toString.call(test3));//输出object Object var test4 = /qwe/; alert(Object.prototype.toString.call(test4));//输出object RegExp var test5 = 1; alert(Object.prototype.toString.call(test5));//输出object Number var test6 = ""; alert(Object.prototype.toString.call(test6));//输出object String var test7 = true; alert(Object.prototype.toString.call(test7));//输出object Boolean
结合以上3种方法,可以对变量做很彻底的类型检测。
相关文章推荐
- typeof、instanceof、Object.prototype.toString.call() 区分对象类型
- js 检测数据类型instanceof/constructor和 Object.prototype.toString.call()
- typeof,instanceof,Object.prototype.toString来判断数据类型
- 判断变量的类型(typeof、instanceof、Object.prototype.toString)
- jquery判断变量类型typeof和Object.prototype.toString.apply()
- 判断js中各种数据的类型方法之 typeof() 和 Object.prototype.toString() 详解
- js中精确判断对象类型--关于typeof 和Object.prototype.toString方法的区别
- 判断一个变量的类型Object.prototype.toString.call
- typeof 和 Object.prototype.toString.call 数据类型判断的区别
- js 中调用 Object.prototype.toString()来检测对象的类型
- 为什么用Object.prototype.toString.call(obj)检测对象类型?
- instanceof, typeof, & Object.prototype.toString
- typeof,instanceof,Object.prototype.toString.call(),js内置对象
- 用Object.prototype.toString.call(obj)检测对象类型原因分析
- Object.prototype.toString.call(obj)检测对象类型?
- typeof 和 Object.prototype.toString 的区别
- 通过Object.prototype.toString.call()--判断数据(基本、引用)类型
- js中通过Object.prototype.toString方法----精确判断对象的类型
- object.prototype.toString()判断类型
- Object.prototype.toString跨框架判断类型