使用toString检测类型升级版

课后整理 2020-12-14

Object.prototype.toString方法返回对象的类型字符串,因此可以用来判断一个值的类型。

由于实例对象可能会重写Object.prototype.toString方法,所以为了得到类型字符串,最好直接使用Object.prototype.toString方法。通过函数的call方法,可以在任意值上调用这个方法,来判断这个值的类型。

Object.prototype.toString.call(value)

不同数据类型的Object.prototype.toString方法返回值如下。

2.5.2节根据这个特性进行设计的,但是受typeof运算符的束缚,设计思路比较僵硬,代码比较笨拙,需要手动进行维护,不是很友好。下面简化了代码,降低了用户检测类型手动维护的烦恼。

【实现代码】

function typeOf(obj){
    var str =  Object.prototype.toString.call(obj);
    return str.match(/\[object  (.*?)\]/)[1].toLowerCase();
};

【应用代码】

console.log( typeOf({}) );                         //  "object"
console.log( typeOf([]) );                           //  "array"
console.log( typeOf(0) );                           //  "number"
console.log( typeOf(null) );                        //  "null"
console.log( typeOf(undefined) );               //  "undefined"
console.log( typeOf(/ /) );                          //  "regex"
console.log( typeOf(new Date()) );             //  "date"

【扩展方法】

在typeOf基础上,扩展方法,专门检测某种类型数据。

['Null', 'Undefined', 'Object', 'Array', 'String', 'Number', 'Boolean',  'Function', 'RegExp'].forEach(function (t) {
    typeOf['is' + t] = function  (o) {
        return typeOf(o) ===  t.toLowerCase();
    };
});

【扩展应用】

console.log( typeOf.isObject({}) );             //  true
console.log( typeOf.isNumber(NaN) );        //  true
console.log( typeOf.isRegExp(true) );         //  false