类型判断
需要判断的类型
// 常要判断的类型
// 'number'
// 'string'
// 'symbol'
// 'bigint'
// 'unll'
// 'undefined'
// 'boolean'
// 'object'
// 'function'
// 'array'
使用原型
Object.prototype.toString.call(999) // "[object Number]"
Object.prototype.toString.call('') // "[object String]"
Object.prototype.toString.call(Symbol()) // "[object Symbol]"
Object.prototype.toString.call(42n) // "[object BigInt]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(true) // "[object Boolean]
Object.prototype.toString.call({a:1}) // "[object Object]"
Object.prototype.toString.call([1,2]) // "[object Array]"
Object.prototype.toString.call(new Date) // "[object Date]"
Object.prototype.toString.call(function(){}) // "[object Function]"
function check_type_by_prototype(target) {
return Object.prototype.toString.call(target)
.toLowerCase()
.replace("[object ", "")
.replace("]", "");
}
使用 typeof
因为历史遗留的原因。typeof null 尝试返回为null失败了,所以要记住,typeof null返回的是object。
typeof 1 // "number"
typeof 'a' // "string"
typeof true // "boolean"
typeof undefined // "undefined"
typeof Symbol() // "symbol"
typeof 42n // "bigint"
typeof null // "object"
typeof NaN // "number"
typeof({a:1}) // "object" 普通对象直接返回“object”
typeof [1,3] // 数组返回"object"
typeof(new Date) // 内置对象 "object"
typeof function(){} // "function"
function check_type_by_typeof(target) {
// 'number'
// 'string'
// 'symbol'
// 'bigint'
// 'unll'
// 'undefined'
// 'boolean'
return typeof target
}
使用 instanceof
可以左边放你要判断的内容,右边放类型来进行JS类型判断,只能用来判断复杂数据类型,因为instanceof 是用于检测构造函数(右边)的 prototype
属性是否出现在某个实例对象(左边)的原型链上。
[1,2] instanceof Array // true
(function(){}) instanceof Function // true
({a:1}) instanceof Object // true
(new Date) instanceof Date // true
obj instanceof Object方法也可以判断内置对象。
缺点:在不同window或者iframe间,不能使用instanceof。