🔥JS类型检测

51 阅读2分钟

✨总结

  1. 使用 typeof 判断基本类型 (除了 null, null 用===来判判断) ,使用 instanceof 来判断引用类型
  2. 或者使用Object.prototype.toString.call(任何类型都能测)直接速通类型检测 😎

JS 中的基本类型(七种):

  1. boolean
  2. null
  3. undefined
  4. number
  5. string
  6. symbol
  7. bigint

JS 中的引用类型(记住下面这些即可):

  1. 普通对象-Object
  2. 数组对象-Array
  3. 正则对象-RegExp
  4. 日期对象-Date
  5. 数学函数-Math
  6. 函数对象-Function

类型转换方法 1: typeof

在 JavaScript 中, typeof 运算符用于检测变量的类型。

typeof 检测基本类型:

  1. boolean
let boolVar = true
console.log(typeof boolVar) // 输出 "boolean"
  1. null
let nullVar = null
console.log(typeof nullVar) // 输出 "object" (注意:这是JavaScript的一个历史遗留问题, `typeof null` 返回 "object") ,如果想要判断`null`,我们可以使用`===`来判断
  1. undefined
let undefVar
console.log(typeof undefVar) // 输出 "undefined"
  1. number
let numVar = 123
console.log(typeof numVar) // 输出 "number"
  1. string
let strVar = 'Hello, World!'
console.log(typeof strVar) // 输出 "string"
  1. symbol (ES6 引入的新类型)
let symbolVar = Symbol('unique')
console.log(typeof symbolVar) // 输出 "symbol"
  1. bigint (ES10 引入的新类型)
let bigIntVar = 12345678901234567890n // n 后缀表示这是一个 BigInt 类型的字面量
console.log(typeof bigIntVar) // 输出 "bigint"

typeof 检测引用类型: 除了函数对象 Function 之外,其他都返回 Object 。这也是 typeof 的一个缺点。

// 函数对象
const func = () => {
  console.log('hello')
}
console.log(typeof func) // function

// 其他对象
let obj1 = {}
console.log(typeof obj1) // object

let obj2 = []
console.log(typeof obj2) // object

let obj3 = new Date()
console.log(typeof obj3) // object

类型转换方法 1: instanceof✨ instanceof 运算符会沿着待测内容的原型链查找, 看它是否能在某个地方找到给定的构造函数。如果能找到, 那么 instanceof 就返回 true, 否则返回 false。

[] instanceof Array// true
[] instanceof Object// true 数组的原型链上能找到Array,也能找到Object

const j = new Jiang()
j instanceof Jiang// true
Jiang instanceof Jiang// false: 自己不在自己的原型链上,所以返回false

再次总结

  1. 使用 typeof 判断基本类型,除了 null, null 使用===。使用 instanceof 来判断引用类型, instanceof基于原型链。
  2. 使用Object.prototype.toString.call(任何类型都能测)直接速通类型检测