JavaScript中各种类型的检测
typeof 'abc'
Object.prototype.toString.call('abc')
typeof 123
Object.prototype.toString.call(123)
typeof true
Object.prototype.toString.call(true)
typeof Object.toString
Object.prototype.toString.call(Object.toString)
typeof undefined
Object.prototype.toString.call(undefined)
undefined === undefined
typeof null
Object.prototype.toString.call(null)
null === null
function isArr(val) {
return Array.isArray(val)
}
typeof [1, 2, 3]
Object.prototype.toString.call([1, 2, 3])
function isObj(val) {
return Object.prototype.toString.call(val) === '[object Object]'
}
typeof {a: 1, b: 'xyz'}
Object.prototype.toString.call({a: 1, b: 'xyz'})
typeof new Date()
Object.prototype.toString.call(new Date())
class MyObj {
constructor(name, age) {
this.name = name
this.age = age
}
}
typeof new MyObj('yyy', 18)
new MyObj('yyy', 18).constructor === MyObj