美文网首页js
判断数据类型`Object.prototype.toString

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

作者: u14e | 来源:发表于2017-02-23 16:09 被阅读10次
    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
    

    相关文章

      网友评论

        本文标题:判断数据类型`Object.prototype.toString

        本文链接:https://www.haomeiwen.com/subject/eksbwttx.html