类型判断在 web 开发中有非常广泛的应用,简单的有判断数字还是字符串,进阶一点的有判断数组还是对象,再进阶一点的有判断日期、正则、错误类型,再再进阶一点还有比如判断 plainObject、空对象、Window 对象等等。
以上都会讲,今天是上半场。
typeof
我们最最常用的莫过于 typeof,注意,尽管我们会看到诸如:
console.log(typeof('yayu')) // string
的写法,但是 typeof 可是一个正宗的运算符,就跟加减乘除一样!这就能解释为什么下面这种写法也是可行的:
console.log(typeof 'yayu') // string
引用《JavaScript权威指南》中对 typeof 的介绍:
typeof 是一元操作符,放在其单个操作数的前面,操作数可以是任意类型。返回值为表示操作数类型的一个字符串。
那我们都知道,在 ES6 前,JavaScript 共六种数据类型,分别是:
Undefined、Null、Boolean、Number、String、Object
然而当我们使用 typeof 对这些数据类型的值进行操作的时候,返回的结果却不是一一对应,分别是:
undefined、object、boolean、number、string、object
注意以上都是小写的字符串。Null 和 Object 类型都返回了 object 字符串。
尽管不能一一对应,但是 typeof 却能检测出函数类型:
function a() {}console.log(typeof a); // function
所以 typeof 能检测出六种类型的值,但是,除此之外 Object 下还有很多细分的类型呐,如 Array、Function、Date、RegExp、Error 等。
如果用 typeof 去检测这些类型,举个例子:
var date = new Date();var error = new Error();console.log(typeof date); // objectconsole.log(typeof error); // object
返回的都是 object 呐,这可怎么区分~ 所以有没有更好的方法呢?
Object.prototype.toString
是的,当然有!这就是 Object.prototype.toString!
那 Object.protototype.toString 究竟是一个什么样的方法呢?
为了更加细致的讲解这个函数,让我先献上 ES5 规范地址:https://es5.github.io/#x15.2.4.2。
在第 15.2.4.2 节讲的就是 Object.prototype.toString(),为了不误导大家,我先奉上英文版:
When the toString method is called, the following steps are taken:
- If the this value is undefined, return "[object Undefined]".
- If the this value is null, return "[object Null]".
- Let O be the result of calling ToObject passing the this value as the argument.
- Let class be the value of the [[Class]] internal property of O.
- Return the String value that is the result of concatenating the three Strings "[object