前言
使用Object.prototype.toString.call(obj)简单实现下检测数据类型的方法。
typeof:用来检测数据类型的运算符;
instanceof:用来检测某个实例是不是属于某个类;
constructor:构造函数 作用和instanceof非常相似;
Object.prototype.toString.call(); 最准确的最常用的方法;
console.log(Object.prototype.toString.call(123)) // [object Number]
console.log(Object.prototype.toString.call('123')) // [object String]
console.log(Object.prototype.toString.call(function(){})) // [object Function]
console.log(Object.prototype.toString.call(/\d/)) // [object RegExp]
console.log(Object.prototype.toString.call(true)) // [object Boolean]
console.log(Object.prototype.toString.call(undefined)) // [object Undefined]
console.log(Object.prototype.toString.call(null)) // [object Null]
console.log(Object.prototype.toString.call(new Date())) // [object Date]
console.log(Object.prototype.toString.call([1, 2])) // [object Array]
console.log(Object.prototype.toString.call({'name': 'Jenny'})) // [object Object]
function A(){};
console.log(Object.prototype.toString.call(new A)) // [object Object]
封装成简便方法:
function getType (value) {
let type = Object.prototype.toString.call(value)
let result = type.match(/\[object (.*?)\]/)[1].toLowerCase()
return result
}
console.log(getType(new Date()) == 'date') // true
console.log(getType([1, 2])) // array
console.log(getType({'name': 'Jenny'})) // object
console.log(getType('str')) // string