js验证对象类型
1. Object.prototype.toString.call()
这是最佳解决方案,可以用作通用方式处理。各种类型的判断依据类似于[object Object],替换的是后边的Object为其他类型。
let x = {
a: 1,
b: 2,
c: 3
}
console.log(Object.prototype.toString.call(x) === '[object Object]'); // true
2. constructor和instanceof
这两个实现的功能是类似的,都不可以判断null和undefined类型,而且相比第一种有个重大的缺陷——在某些ie版本中存在跨iframe问题,由于每个iframe下都有自己的一套原型链,跨iframe后导致实例化后的对象不共享原型链。
let x = {
a: 1,
b: 2,
c: 3
}
console.log(x.constructor === Object); // true
console.log(x instanceof Object); // true
3. typeof
typeof可以说是最常用的方式,但是这个仅能够判断基本类型,一般使用的时候和第二种方法组合可以实现第一种的功能。
let x = {
a: 1,
b: 2,
c: 3
}
let y = [];
console.log(typeof x); // object
console.log(typeof y); // object
console.log(typeof y && y.constructor === Array); // true