JS的数据类型

基本有5种基本数据类型:StringNumberBooleanNullundefined
1种复杂的数据类型Object,比如Objectarrayfunctiondata等。

ES6新增了一种基本数据类型symbol

1. Object.prototype.toString.call()(推荐使用)

该方法最繁琐,但最通用(简单和复杂类型都可以检测)
let a = [];let b = function () {}let c = 4;let d = null;console.log(Object.prototype.toString.call(a));console.log(Object.prototype.toString.call(b));console.log(Object.prototype.toString.call(c));console.log(Object.prototype.toString.call(d));// [object Array]// [object Function]// [object Number]// [object Null]

2. typeof(有bug)

typeof能检测到的数据有functionstringnumberbooleanundefinedsymbol,其他所有的类型,都会被检测为object

let a = [];let b = function () {};let c = 4;console.log(typeof a);console.log(typeof b);console.log(typeof c);// object// function// number

bug实例
null是基本数据类型,但使用typeof会显示object

console.log(typeof null);// object
在 JS 的最初版本中,使用的是 32 位系统,为了性能考虑使用低位存储了变量的类型信息,000 开头代表是对象,然而 null 表示为全零,所以将它错误的判断为 object 。虽然现在的内部类型判断代码已经改变了,但是对于这个 Bug 却是一直流传下来。

3. instanceof(只能判断对象类型)

let a = [];let b = function () {};let c = 4;let d = new Number(4);console.log(a instanceof Array);console.log(b instanceof Function);console.log(c instanceof Number);console.log(d instanceof Number);// true// true// false// true
在上例代码中可以看出必须通过包装类Number把数字4转换成对象,才能准确判断他的数据类型。

4. constructor(不稳定)

let a = [];let b = function () {};let c = 4;let d = null;console.log(a.constructor === Array);console.log(b.constructor === Function);console.log(c.constructor === Number);console.log(d.constructor === null);// true// true// true// 控制台报错
  1. null 和 undefined 是无效的对象,因此是不会有 constructor 存在的。
  2. 函数的 constructor 是不稳定的,当开发者重写 prototype 后,原有的 constructor 引用会丢失,constructor 会默认为 Object。