判断数据类型 高于 typeof

148 阅读1分钟

1、判断数据类型基础

console.log('undefined',    Object.prototype.toString.call(undefined))
console.log('null',         Object.prototype.toString.call(null))
console.log('string',       Object.prototype.toString.call('string'))
console.log('number',       Object.prototype.toString.call(1))
console.log('boolean',      Object.prototype.toString.call(true))
console.log('object',       Object.prototype.toString.call({}))
console.log('array',        Object.prototype.toString.call([]))
console.log('function',     Object.prototype.toString.call(function(){}))

数据类型.png

2、核心方法

function isString(obj){
    return Object.prototype.toString.call(obj) === "[object String]"
}

function isString(obj){
    return Object.prototype.toString.call(obj) === "[object Boolean]"
}

3、闭包

function isType(type){
    return function(obj){
        console.log(`[object ${type}]`)
        return Object.prototype.toString.call(obj) === `[object ${type}]`
    }
}
var isString = isType('String')
var isArray = isType('Array')
var isObject = isType('Object')

4、for循环创建判断数据类型的函数(高阶函数。 柯里化函数)


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