JS判断变量类型

目前接触到的共有四种方法:

1、typeof,

typeof对大多数的类型判断都是正确的,返回的都是小写的字符串类型,但是无法区分数组,null,和真正的Object,它的判断都是"object"。

--------2023.02.11读javaScript秘籍--------

发现typeof不仅无法区分数组,null和真正的object,它在不同环境下判断不同的对象是,返回的竟然有function,有unknown,以下是电子书截图:

 

 

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,否则会抛出异常。


2019.07.05看了《你不知道的JavaScript》原型链章节以后,发现此处理解有误。现更正如下:

instanceof 操作符的左操作数是一个普通的对象,右操作数是一个函数。a instanceof Foo 回答的问题是:在 a 的整条 [[Prototype]] 链中是否有指向 Foo.prototype 的对象。

测试了以下场景:

字符串:

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.

这里给出了一篇深入底层的文章链接,该文章从底层彻底讲解了instanceof的问题关键所在:https://www.ibm.com/developerworks/cn/web/1306_jiangjj_jsinstanceof/index.html

4、constructor.name

该方式大部分情况下都可以,弊端是undefined,或者null没有constructor。好像跟3有点像,3是表示constructor.prototype,首先得有constructor才能有constructor.prototype。

用法例:

var a = ''

a.constructor.name // 返回String 

很是推荐第二种,最全。

posted @ 2019-05-15 18:17  liujiekun  阅读(9625)  评论(0编辑  收藏  举报