typeof
说到js检查数据类型,基本想到的就是typeof
,但是这个只能检查简单类型,遇到复杂类型就不准确了。
- 简单类型
typeof 'abc' // string
typeof false // boolean
typeof 1 // number
- 复杂类型
typeof ['1','abc'] // object
typeof {a:'1',b:'a'} // object
遇到复杂类型的时候,判断就不准确了,那怎么判断才好呢?有两种判断方式
- 构造函数
const arr = [1, '2', 3];
arr.constructor === Array // true
arr.constructor === Object // false
arr.constructor // [Function: Array]
// 简单类型
const string = [1, '2', 3];
arr.constructor === Number // true
arr.constructor // [Function: Number]
- 原型方式
const arr = [1,2,3]
const type = Object.prototype.toString.call(arr)
type === '[object Array]' // true
以下给两个工具类,视情况选择
工具一:==返回值是布尔类型==
/* 类型检查 返回 true/flase */
对应方式一
class jsType {
static isArray(value) {
return value.constructor === Array
}
static isObject(value) {
return value.constructor === Object
}
static isUndefined(value) {
return value === undefined
}
static isString(value) {
return value.constructor === String
}
static isNull(value) {
return value === null
}
static isFunction(value) {
return value.constructor === Function
}
static isNumber(value) {
return value.constructor === Number
}
static isBoolean(value) {
return value.constructor === Boolean
}
}
// 测试示例
jsType.isArray([1, 2, 3])
jsType.isNumber(1)
jsType.isString('字符串')
jsType.isBoolean(true)
jsType.isObject({ name: 'ipenman', age: 12 })
jsType.isFunction(function() {})
jsType.isNull(null)
jsType.isUndefined(undefined)
工具二:==返回值是该对象的数据类型==
/* 类型检查 返回 true/flase */
function jsType(value) {
const oType = {
'[object Array]': 'Array',
'[object Object]': 'Object',
'[object Number]': 'Number',
'[object String]': 'String',
'[object Boolean]': 'Boolean',
'[object Undefined]': 'undefined',
'[object Null]': 'null',
'[object Function]': 'Function',
'[object Date]':'Date'
}
const sType = Object.prototype.toString.call(value)
for (const item in oType) {
if (sType === item) return oType[item]
}
}
这两个工具类就能解决复杂类型的判断了,好了到此结束!
网友评论