JavaScript 数据类型判断

前言

JavaScript 数据类型有很多种, 日常开发中判断数据类型是必不可少的工作,简单的有判断数字还是字符串,复杂一点的有判断数组还是对象等等,所以总结了一下判断数据类型具体有哪些方法。

typeof

typeof 操作符返回一个字符串,表示未经计算的操作数的类型。

typeof "abc"; // string
typeof 1; // number
typeof true; // boolean
typeof undefined; // undefined
typeof Symbol(); // symbol
typeof function foo() {}; // function

typeof []; // object
typeof {}; // object
typeof new String("abc"); // object
typeof new Number(1); // object
typeof null; // object
复制代码

instanceof

instanceof 运算符 用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

let Person = function() {}
let person = new Person()
person instanceof Person // true
let a = new String('aaa')
a instanceof String // true
let str = 'aaa'
str instanceof String // false
复制代码

Object.prototype.toString

所有 typeof 返回值为 object 的对象都包含一个内部属性 [[Class]],这个属性是引擎内部用来判断一个对象属于哪种类型的值的,无法直接访问,只能通过间接方法 Object.prototype.toString() 来查看。

当 toString 方法被调用的时候,下面的步骤会被执行:

  1. 如果 this 值是 undefined,就返回 [object Undefined]
  2. 如果 this 的值是 null,就返回 [object Null]
  3. 对 this 进行类型转换成对象ToObject(this),并将结果保存到 O
  4. 让 class 成为 O 的内部属性 [[Class]] 的值
  5. 最后返回由 "[object " 和 class 和 "]" 三个部分组成的字符串

[[Class]] 的值是判断数据类型的关键,一共有多少种类型呢,经过测试,至少可以识别以下 14 种类型

Object.prototype.toString.call(undefined) // '[object Undefined]'
Object.prototype.toString.call(null) // '[object Null]'
Object.prototype.toString.call('a') // '[object String]'
Object.prototype.toString.call(0) // '[object Number]'
Object.prototype.toString.call(true) // '[object Boolean]'
Object.prototype.toString.call([]) // '[object Array]'
Object.prototype.toString.call({}) // '[object Object]'
Object.prototype.toString.call(()=>{}) // '[object Function]'
Object.prototype.toString.call(new Date()) // '[object Date]'
Object.prototype.toString.call(new Error()) // '[object Error]'
Object.prototype.toString.call(/a/g) // '[object RegExp]'
Object.prototype.toString.call(Math) // '[object Math]'
Object.prototype.toString.call(JSON) // '[object JSON]'
//除了以上 13 种之外,在函数内部
function foo() {
  console.log(Object.prototype.toString.call(arguments));
}
foo() // '[object Arguments]'
复制代码

通过 Object.prototype.toString() 返回的字符串,我们可以封装一个检测数据类型的万能方法,思路是 基本数据类型typeof 检测, null引用数据类型Object.prototype.toString() 检测。

function getType(o) {
  if (typeof o !== "object") return typeof o;
  return Object.prototype.toString.call(o).slice(8, -1).toLocaleLowerCase();
}
console.log(getType([]))
//array
复制代码

总结

  • typeof 可以判断基本数据类型(null 除外),无法判断引用数据类型(function 除外),返回的是字符串。
  • instanceof 可以准确判断引用数据类型,返回布尔值。
  • Object.prototype.toString 通过访问内部属性[[Class]],可以判断任意的数据类型,返回的是经过拼接的字符串,需要进行截取。

おすすめ

転載: juejin.im/post/7075203307043553311