总的来说,判断数据类型有很多种方法:
- typeof 基本类型可以,但是对于复杂类型不准确
- instanceof
- constructor 比较准确(只是有时constructor会被改变)
- isPrototypeOf
- Object.prototype.toString.call() 最好的
typeof 返回值:
undefined:未定义 (只声明,但是未定义的也是undefined)
boolean: 布尔值
number: 数值
string: 字符串
object: 对象或null
function: 函数
constructor返回值:
就是其对应的构造函数(但是constructor有可能被修改)
instanceof返回值:
判断对象是否属于这个构造函数(查找对象与构造函数在原型链上是否有关系)
Object.prototype.toString.call()返回值
最准确的
[object Number]
[object String]
[object Boolean]
[object Array]
[object Object]
[object Function]
[object RegExp]
1 | // 基本数据类型 |
输出结果:
1 | number function Number() { [native code] } [object Number] |