js

判断数据类型`Object.prototype.toString

2017-02-23  本文已影响10人  u14e
var isString = function(obj) {
    return Object.prototype.toString.call(obj) === '[object, String]';
}
var isArray = function(obj) {
    return Object.prototype.toString.call(obj) === '[object, Array]';
}
var isNumber = function(obj) {
    return Object.prototype.toString.call(obj) === '[object, Number]';
}
var isType = function(type) {
    return function(obj) {
        Object.prototype.toString.call(obj) === `[object ${type}]`;
    }
}

var isString = isType('String');
var isArray = isType('Array');
var isNumber = isType('Number');

终极方案:

var Type = {};
for (var i = 0, type; type = ['String', 'Array', 'Number'][i++];) {
    (function(type){
        Type[`is${type}`] = function(obj) {
            return Object.prototype.toString.call(obj) === `[object ${type}]`;
        };
    })(type)
}

Type.isArray([]);     // true
Type.isString('str');   // true
上一篇 下一篇

猜你喜欢

热点阅读