js判断各种数据类型

102 阅读1分钟

一、typeof

typeof用法有两种,typeof xxx 和 typeof(xxx)

typeof 1                  //Number
typeof ''                 //String
typeof true               //Boolean
typeof null               //Object
typeof undefined          //undefined
typeof (function(){})     //Function
typeof []                 //Object
typeof {}                 //Object

可以看出,typeof并不能区分null,{},[]

二、Object.prototype.toString.call() 可以精准的判断数据的类型

我们来看看代码

let getType = Object.prototype.toString

console.log(getType.call(null))   //[object Null]
console.log(getType.call({}))     //[object Object]
console.log(getType.call([]))     //[object Array]
console.log(getType.call(1))     //[object Number]
console.log(getType.call(''))     //[object String]
console.log(getType.call(true))     //[object Boolean]
console.log(getType.call(function() {}))     //[object Function]
console.log(getType.call(undefined))     //[object Undefined]

这里参考一下一位大佬封装的方法,文章链接

const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target)
const selfIsArray = isType('Array')
//对稀疏数组的处理
Array.selfIsArray || (Object.defineProperty(Array, 'selfIsArray', {
    value: selfIsArray,
    enumerable: false,
    configurable: true,
    writable: true
}))
console.log(selfIsArray([])); // true

这是目前我了解到的比较好的判断方法,欢迎大家讨论指正,有更多更好的方法可以谈论谈论

----------前端小白