JS判断变量类型
目前接触到的共有四种方法:
1、typeof,
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。typeof对大多数的类型判断都是正确的,但是无法区分数组,null,和真正的Object,它的判断都是Object。
2、Object.prototype.toString.call(),
Object.prototype.toString.call()的方法,各种类型都合适,判断准确,也是我准备长期使用的一种方法,返回的结果如[Object Array],据我所知,jQuery的内部工具、vue的内部工具,mock的内部工具,都是采用的这种方法。
jQuery实现方法,采用对象方式存储,
初始化变量class2type={},
// Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); 然后类型判断方法: type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : // 返回对象中有的结果 typeof obj; // 返回typeof本身可以判断的。 } Vue内部判断方法,简单粗暴: var _toString = Object.prototype.toString; function toRawType (value) { return _toString.call(value).slice(8, -1) // 直接从第八位返回到倒数第二位 } Mock的内部工具方法, 使用正则: Util.type = function type(obj) { return (obj === null || obj === undefined) ? String(obj) : Object.prototype.toString.call(obj).match(/\[object (\w+)\]/)[1].toLowerCase() }3、instanceof
MDN给出的解释是:instanceof
运算符用来检测 constructor.prototype
是否存在于参数 object
的原型链上。
instanceof右侧要求是对象,而不能是null或者undefined,否则会抛出异常。
测试了以下场景:
字符串:
var a = ''; a instanceof String // false
var a = new String(''); a instanceof String //true,
数字:
var a = 3; a instanceof Number // false
var a = new Number(3); a instanceof Number //true,
数组:
var a= [1,2,3]; a instanceof Array //true
var a = new Array(1,2,3); a instanceof Array //true
函数:
var a = function(){} a instanceof Fuction // true
var a = new Function(); a instanceof Function //true
// 对象
var a= {};a instanceof Object //true
// 正则
var a= /ppp/; a instanceof RegExp // true
// undefined,null的没法说了
总结:凡是简单字面量的像number,string的必须用new才识别,而复杂点的像数组,对象,函数,正则都可以直接用。但是原型链上的返回都是true,比如
var a = new String(''); a instanceof String // true, a instanceof Object肯定也是true.
4、constructor.name
该方式大部分情况下都可以,弊端是undefined,或者null没有constructor。好像跟3有点像,3是表示constructor.prototype,首先得有constructor才能有constructor.prototype。
用法例:
var a = ''
a.constructor.name // 返回String
很是推荐第二种,最全。
