使用toString()检测对象类型

能够经过toString() 来获取每一个对象的类型。为了每一个对象都能经过 Object.prototype.toString() 来检测,须要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式来调用,传递要检查的对象做为第一个参数,称为thisArgapp

var toString = Object.prototype.toString;

toString.call(new Date); // [object Date]
toString.call(new String); // [object String]
toString.call(Math); // [object Math]

//Since JavaScript 1.8.5
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]

能够写个函数来判断个数据类型函数

function consoleType(obj) {
        return (Object.prototype.toString.apply(obj));
    }

    consoleType([]);    //  [object Array]
    consoleType(null);  //  [object Null]
    consoleType(undefined); // [object Undefined]
    consoleType(0);     // [object Number]
    consoleType(new Date);  //  [object Date]
    consoleType({});        //  [object Object]
    consoleType(function () {});    //  [object Function]
    consoleType(NaN);           //  [object Number]
    consoleType('a');           //  [object String]
    consoleType(/\d/);           //  [object RegExp]
 

参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/toString#Using_toString()_to_detect_object_classthis

相关文章
相关标签/搜索