返回数据类型,包含这7种: number、boolean、symbol、string、object、undefined、function。
typeof null 返回类型错误,返回object
引用类型,除了function返回function类型外,其他均返回object。
其中,null 有属于自己的数据类型 Null , 引用类型中的 数组、日期、正则 也都有属于自己的具体类型,而 typeof 对于这些类型的处理,只返回了处于其原型链最顶端的 Object 类型,没有错,但不是我们想要的结果。
判断已知对象类型的方法.instanceof 后面一定要是对象类型,并且大小写不能错,该方法适合一些条件选择或分支。
toString() 是 Object 的原型方法,调用该方法,默认返回当前对象的 [[Class]] 。这是一个内部属性,其格式为 [object Xxx] ,其中 Xxx 就是对象的类型。
对于 Object 对象,直接调用 toString() 就能返回 [object Object] 。而对于其他对象,则需要通过 call / apply 来调用才能返回正确的类型信息。
判断类型举例:
// 是否字符串
const isString = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'String'
}
// 是否数字
const isNumber = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Number'
}
// 是否boolean
const isBoolean = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Boolean'
}
// 是否函数
const isFunction = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Function'
}
// 是否为null
const isNull = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Null'
}
// 是否undefined
const isUndefined = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Undefined'
}
// 是否对象
const isObj = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Object'
}
// 是否数组
const isArray = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Array'
}
module.exports = {
isString,
isNumber,
isBoolean,
isFunction,
isNull,
isUndefined,
isObj,
isArray
}