如何准确判断变量类型

179 阅读1分钟
const Type = {};
const types = ['Undefined', 'Null', 'String', 'Number', 'Boolean', 'Object', 'Array', 'Function'];

types.map(type => {
    Type[`is${type}`] = function (obj) {
        return Object.prototype.toString.call(obj) === `[object ${type}]`
    }
})


Type.isArray([1,2,3]) // true;
Type.isObject({})  // true;
Type.isFunction(function(){}) // true;
Type.isString('123') // true;
Type.isUndefined(undefined) //true;