js如何判断(复杂)数据类型

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会显示objectprototype

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。
相关文章
相关标签/搜索