typeof {} //'object'
typeof [] //'object'
typeof null //'object'
typeof new String() //'object'
typeof NaN //'number'
const var reg = /pop/g
typeof reg //'object'
我们都知道用typeof去判断数组,对象得到了都是Object,因为在js中数组是特殊的对象,还有null等,大部分情况下typeof是可信的,但总有一些特殊情况。估以下方法可具体判断类型。
var toString = Object.prototype.toString
function isObject(obj) {
return toString.call(obj) === '[object Object]'
}
function isString(obj) {
return toString.call(obj) === '[object String]'
}
function isArray(obj) {
return toString.call(obj) === '[object Array]'
}
function isFunction(obj) {
return toString.call(obj) === '[object Function]'
}