JS数据类型判断–避坑指南

2次阅读

共计 1434 个字符,预计需要花费 4 分钟才能阅读完成。

1. 常用的 typeof
对于 array、object、null 的判断是不友好的,可以看下图的执行结果。

var obj = {
number:123,
string: ‘123’,
bool: true,
obj: {},
arr: [],
n: null,
undef: undefined,
fn: function () {}
}

for(key in obj) {
console.log(key + “: ” + typeof obj[key])
}
2. instanceof
instanceof 测试构造函数的 prototype 属性是否出现在对象的原型链中的任何位置。如果你了解原型链,你会知道原型链的复杂性,instanceof 得到的值并不是固定不变的,它会沿着原型链查找,最明显的是所有的基本数据类型都继承与 Object.protype.
[任何数据类型] instanceof Object
> true
如下图:
3. 最终方案:Object.prototype.toString.call()
下面是兼容性方案最好、最全面、也是最有效的:下面有两种实现方式 (原型方法和全局方法),可以根据自己的需要选择。
(function () {
function isType(type,data) {
// data 是全局方法时使用的, 原型方法可不填
return Object.prototype.toString.call(data || this) === ‘[object ‘ + type + ‘]’
}
// 全局方法支持 null 和 undefined
// window.isType = isType

// 添加到数据类型的原型中,不支持 null 和 undefined
Object.defineProperty(Object.prototype,’isType’,{
value:isType,
writable:true,
enumerable:false,
configurable:true
});
})()

使用方式:
var str = ‘abc’;
// 全局方法
isType(‘String’, str) // True

// 原型方法
str.isType(‘String’)

测试代码:
var obj = {
test: {
number:123,
string: ‘123’,
obj: {},
bool: true,
arr: [],
n: null,
undef: undefined,
fn: function () {

}
}
}
// 原型方法不支持 null 和 undefined,请用“===”
console.log(obj.test.number.isType(‘Number’))
console.log(obj.test.number.isType(‘String’))

console.log(obj.test.string.isType(‘String’))
console.log(obj.test.string.isType(‘Number’))

console.log(obj.test.obj.isType(‘Object’))
console.log(obj.test.obj.isType(‘Array’))

console.log(obj.test.arr.isType(‘Array’))
console.log(obj.test.arr.isType(‘Object’))

console.log(obj.test.fn.isType(‘Function’))
console.log(obj.test.fn.isType(‘Object’))

正文完
 0