JS灵巧判断7种类型的方式

10,074 阅读5分钟

类型:

JavaScript 中有七种内置类型:
  1. 空值 (null)
  2. 未定义 (undefined)
  3. 布尔值 (boolean)
  4. 数字 (number)
  5. 字符串 (string)
  6. 对象 (object)
  7. 符号 (symbol,ES6中新增)

在 JS 中呢,有很多坑,本文章将结合 undersoce.js源码 和我所总结的方法准确判断这六种类型,第七种也会提供一种判断思路;

先来一个小测试:

首先,大家都熟悉的一种判断方式 typeof,这是一种虽然老掉牙但是有些实用的方式 :

typeof null			// "object"			<= 在后面文章里你会看到,巨坑!!!

typeof undefined	        // "undefined"

typeof true			// "boolean"

typeof 42		        // "number"

typeof "42"			// "string"

typeof {life: 42}               // "object"

typeof Symbol()		        // "symbol"


// ------------后面3种是单独提出来的注意事项------------------

typeof void 0		       // "undefined"	<= 这是一个非常实用的技巧,我将在后面解释;

typeof [1,2,3]		       // "object"  <= 数组 其实也是对象,巨坑!!!

typeof function a() { }		// "function" 

巧用 “ ! ” 号:

!null			   // true			   <= 这是一个非常巧妙的技巧,下面将解释;

!undefined		   // true			   <= 这是一个非常巧妙的技巧,下面将解释;

------------我们不一样!!!------------

!123			  // false

!true			  // false

!{a: 123}		  // false

!function a() { }         // false

!'123'			  // false

有了这个区别,我们可以做一些有趣的事情,这是在 undersoce.js 源码里面学到的技巧,这样能够准确地排除 null 和 undefined

无敌法 “ .toString.call() ”:

当然 Object.prototype.toString.call 也可以换成 Object.prototype.toString.apply

Object.prototype.toString.call(null)	    // "[object Null]"

Object.prototype.toString.call(undefined)	// "[object Undefined]"

Object.prototype.toString.call(123)			// "[object Number]"

Object.prototype.toString.call(true)		// "[object Boolean]"

Object.prototype.toString.call('123')		// "[object String]"

Object.prototype.toString.call({a: 123})	// "[object Object]"

Object.prototype.toString.call(Symbol())	// "[object Symbol]"


// ---------------单独出来讲的几个注意事项---------------------

Object.prototype.toString.call([1,2,3])	// "[object Array]"

Object.prototype.toString.call(function a() { })	// "[object Function]" 其实函数也是object类型

Object.prototype.toString.call(new Date)	// "[object Date]"	日期对象

Object.prototype.toString.call(Math)		// [object Math]	数学函数对象

Object.prototype.toString.call(function a() { })	// "[object Function]" 其实函数也是object类型

注1:这种方式存在兼容性问题,具体兼容性问题点击 这里 ,JavaScript 1.8.5,无法完全检测上述情况。

注2:使用这套技巧,能够准确地分辨这7种类型甚至更多更精确,而 typeof 却无法区分完全!!!!!

来看看 " constructor "吧:

这种方式是判断对象的构造函数是谁,至于什么是构造函数我将在另一篇文章写道;

var n1 = null;
n.constructor			  // 报错:因为 null 是 JS 原型链的起点,没有构造函数;

var u = undefined;
u.constructor			  // 报错:它也没有构造函数;

var a = [1, 2, 3];
a.constructor === Array;   // true	数组

var n = 123;
n.constructor === Number;  // true	数字

var s1 = '123';
abc.constructor === String	// true	字符串

var o = {a: 123};
o.constructor === Object;   // true 对象

var s = Symbol()
abc.constructor === Symbol	// true 符号

------------------单独出来讲的几个注意事项----------------------

var arr = [1, 2, 3];
arr.constructor === Array	// true 数组 能够很好地区分

var fun = function a() { };
fun.constructor === Function  // true 函数

var abc = new Date();
abc.constructor === Date;	 // true 日期 

var abc = new RegExp();
abc.constructor === RegExp;	// true 正则 

var abc = Math
abc.constructor === Math;	// false 不可以像Object.prototype.toString.call()一样区分;

abc.constructor === Object   // true 事实上没有Math这个构造函数,Math的构造函数在 Object上的

最后一招 “ instanceof ”:

注意:使用对象必须是一个 object ;

// 语法: object instanceof constructor;

var n1 = 123;			 // n 是类型为 Number 的元素!!!不是对象!!!
typeof n1;				 // "number"	回想一下我们有7种类型
n1 instanceof Number;	  // false	 function Number() { }

var n2 = new Number(123)  // 现在 n2 是一个 object 元素!!!
typeof n2;				 // "object"
n2 instanceof Number;	  // true

正如,上述方式所说,这种方式只适合判断 object !!!

var a = [1, 2, 3];		// 在最开始就声明了,数组也是对象,此法可以用来判断数组;

a instanceof Array;		// 而这个对象的构造函数是 function Array() { }

// 虽然 typeof null 也是 object 但这是最底层的元素

在这里我就不过多举例子了,你如果不知道原型链的东西,那就先记住 instanceof 能判断数组吧!!

阅读声明:法1都是来源于 underscore.js 源码:

空值 (null):

法1:直接用严格等于判断。
var isNull = function (obj) {
	return obj === null;
};

这是最直接并且有效的方式;

法2:巧妙地利用 ! null 的结果为 true:
var isNull = function (obj) {
	return !obj && typeof obj === "object";
};

此方法虽然很巧妙,但是没有法1直接;

未定义 (undefined)

法1:这是最推荐的方式。
var isUndefined = function (obj) {
	return obj === void 0;
}

很多常见的工具库都采用这种方式,极力推荐!!!;

法2:直接利用 typeof 判断:
var isUndefined = function (obj) {
	return typeof obj === "undefined";
}

这种方式,也是相对稳定的;

注意:

  1. 在全局条件下 undefined 是不可以被修改的。
  2. 在局部条件下 undefined 在某种情况下是可以被修改的。
  3. 请狠狠地戳这里,看官方文档解释。
(function(undefined) {
   console.log(undefined);        // "123"
})('123')

布尔值 (boolean)

这里其实我也有疑惑,为什么 underscore.js 会这样判断,读者知道可以联系我;

var toString = Object.prototype.toString;

var isBoolean = function (obj) {
	return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
}

类似地,我们采用 .constructor 和 typeof 的方式也可以实现判断。

数字 (number)

var toString = Object.prototype.toString;

var isNumber = function (obj) {
	return toString.call(obj) === '[object Number]';
}

类似地,我们采用 constructortypeof 的方式也可以实现判断。

字符串 (string)

var toString = Object.prototype.toString;

var isString = function (obj) {
	return toString.call(obj) === '[object String]';
}

类似地,我们采用 constructortypeof 的方式也可以实现判断。

对象 (object)

var toString = Object.prototype.toString;

var isObject = function (obj) {
	var type = typeof obj;
	return type === 'function' || type === 'object' && !!obj;
}

这里,是我最疑惑的地方,为什么要用 !!obj

  1. typeof null === object 结果为 true ;
  2. 最开始我已经讲了一种,!obj 的方式,nullundefined 返回结果都为 true 而其他类型为 false;
  3. 以上面这种实现方式,如果传递值为 null 的时候,就会被 !!obj 过滤掉;

或者动手试试,将 && !!obj 删掉,看看能否达到预期效果。

其他:

其实上文已经给出思路实现,Date, Math, RegExp等内置对象,我就不详谈了,用得较少:

数组(Array)

法1: 最稳妥的办法:
Object.prototype.toString.call([1,2,3])	// "[object Array]"

老老实实地用这个方法吧!!!

法2:instanceof 法,仅为拓展:
var a = [1, 2, 3];		// 在最开始就声明了,数组也是对象,此法可以用来判断数组;

a instanceof Array;		// 而这个对象的构造函数是 function Array() { }
法3:构造函数法,仅为拓展
var a = [1, 2, 3];
a.constructor === Array;   // true	数组

注:如果 a = null ,还要报错,这种方式坚决不推荐!!!

法4:检查原型的构造函数,仅为拓展:
var a = [1, 2, 3];

a.__proto__.constructor === Array

其实法2-4都是属于一种思路,判断这个对象的构造函数是否为数组,仅仅实现方式不同罢了。

参考和鸣谢:

  • 《你不知道的JavaScript(中)》;
  • Underscore.js 源码;
  • http://www.jb51.net/article/79939.htm
  • https://developer.mozilla.org/zh-CN/docs/Web/JavaScript