js数据类型判断

    16

JS中的数据类型

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

检测办法

  1. typeof 运算符
  2. instanceof [原型链]
  3. constructor [构造函数]
  4. Object.prototype.toString.call([value]) 检测数据类型
  5. Array.isArray([value]) 检测一个值是否为数组

typeof

  1. 可以识别基本数据类型 nullobject
  2. 引用类型为object和function

利用二进制检测,二进制前3位存储

  • 000: 对象
  • 010: 浮点数
  • 100:字符串
  • 110:布尔
  • 1:整数
  • null的二进制全为000所以是object

instanceof

基于原型链检查

[] instanceof Array

function isInstanceOf(instance, constructor) {
    const list = ['string', 'number', 'boolean', 'undefined', 'symbol']
    const type = typeof instance
    const isBasicVal = instance === null || list.indexOf(type) > -1
    const prototype = constructor.prototype
    let proto = isBasicVal ? null : instance.__proto__
    while (true) {
        if (proto === null) return false;
        if (proto === prototype) return true;
        proto = Object.getPrototypeof(proto);
    }
}

Contructor

[].constructor===Array

缺点:在自身实例上判断、容易被修改

Object.prototype.toString.call()

Object.prototype.toString({})       // "[object Object]"
Object.prototype.toString.call([])  //"[object Array]"
Object.prototype.toString.call('1') // "[object String]"

Array.isArray

判断是否是数组

Array.isArray([]) // true
Array.isArray(1) // false

Object.prototype.isPrototypeOf

Array.prototype.isPrototypeOf([])

Object.getPrototypeOf

Object.getPrototypeOf([]) === Array.prototype;
评论区
共有评论 0
暂无评论