你的浏览器不支持canvas

Enjoy life!

javascript - 判断变量类型

Date: Author: JM

本文章采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可。

一、 typeof

    const a = 1
    const b = 'b'
    const c = new Object()
    const d = /hello/
    const e = function () {}
    const f = undefined
    const g = null
    const h = []
    const i = true

    console.log(`a = 1 的类型为:${typeof a}`)
    console.log(`b = 'b' 的类型为:${typeof b}`)
    console.log(`c = new Object() 的类型为:${typeof c}`)
    console.log(`d = /hello/ 的类型为:${typeof d}`)
    console.log(`e = function () {} 的类型为:${typeof e}`)
    console.log(`f = undefined 的类型为:${typeof f}`)
    console.log(`g = null 的类型为:${typeof g}`)
    console.log(`h = [] 的类型为:${typeof h}`)
    console.log(`i = true 的类型为:${typeof i}`)

judgeType

二、instanceof

  • instanceof 主要用来判断引用类型属于哪一类
  • demo
  const reg = new RegExp()
  const array = []
  const obj = new Object()
  const fn = function () {}

  console.log(`reg instanceof RegExp: ${reg instanceof RegExp}`)
  console.log(`array instanceof Array:  ${array instanceof Array}`)
  console.log(`obj instanceof Object:  ${obj instanceof Object}`)
  console.log(`fn instanceof Function:  ${fn instanceof Function}`)

judgeType

三、Object.prototype.toString.call()

  const a = 1
  const b = 'b'
  const c = new Object()
  const d = /hello/
  const e = function () {}
  const f = undefined
  const g = null
  const h = []
  const i = true

  console.log(`a = 1 的类型为:${Object.prototype.toString.call(a)}`)
  console.log(`b = 'b' 的类型为:${Object.prototype.toString.call(b)}`)
  console.log(`c = new Object() 的类型为:${Object.prototype.toString.call(c)}`)
  console.log(`d = /hello/ 的类型为:${Object.prototype.toString.call(d)}`)
  console.log(`e = function () {} 的类型为:${Object.prototype.toString.call(e)}`)
  console.log(`f = undefined 的类型为:${Object.prototype.toString.call(f)}`)
  console.log(`g = null 的类型为:${Object.prototype.toString.call(g)}`)
  console.log(`h = [] 的类型为:${Object.prototype.toString.call(h)}`)
  console.log(`i = true 的类型为:${Object.prototype.toString.call(i)}`)

judgeType


对于本文内容有问题或建议的小伙伴,欢迎在文章底部留言交流讨论。