js数据类型判断三种方法各自优缺点

typeof

  • 检测方法

    主要用于检测基本类型.

  • 缺点: 无法区分 引用类型

     引用类型:object。里面包含的 function、Array、Date。
    
  • 优点 方便快捷 代码量少 区分基本类型正常

     基本类型:Number、String、Boolean、Null、undefined、object、symbol、bigInt。
    
typeof(123) //number
typeof('123')// string

typeof({})//object
typeof([])//object
typeof(new Date) //object

instanceof

  • 主要用于检测引用类型

查找方在对应的值原形链上有.prototype有无对应的,返回true;否则返回false

  • 缺点

    检测基本数据类型较为麻烦 检测前必须要实力对应的数据类型,否则检测不准确

    优点:

    检测引用类型准确


console.log(123 instanceof Object);  //false
console.log(new Number(123) instanceof Number); //true

console.log(new String('123') instanceof String);  //true
console.log('123' instanceof String);  //false

console.log([] instanceof Array);  //true
console.log({} instanceof Object); //true

Object.prototype.toString.call

  • 缺点
    代码量过长
  • 优点
    检测类型准确,无论是基本类型还是引用引用类型都可检测
console.log(Object.prototype.toString.call({})); //[object Object]

console.log(Object.prototype.toString.call([])); //[object Array]

console.log(Object.prototype.toString.call(false)); //[object Boolean]

console.log(Object.prototype.toString.call(null)); //[object Null]

console.log(Object.prototype.toString.call('1123')); //[object String]

console.log(Object.prototype.toString.call(Symbol()));//[object Symbol]

console.log(Object.prototype.toString.call(new Date)); //[object Date]

//..... 对此方法来封装 额这一坨优点像 下面我们来简便代码
function isType (data) {
  if (data === '') return '';
  switch (Object.prototype.toString.call(data))
  {
    case '[object Object]':
      return 'Object';
    case '[object Number]':
      return 'Number';
    case '[object Array]':
      return 'Array';
    case '[object Boolean]':
      return 'Boolean';
    case '[object Null]':
      return 'Null';
    case '[object Undefined]':
      return 'Undefined';
    case '[object String]':
      return 'String';
    case '[object Symbol]':
      return 'Symbol';
    case '[object Date]':
      return 'Date';
    case '[object BigInt]':
      return 'BigInt';
    case '[object Function]':
      return 'Function';
  }
}
//第二种方法最终版

function isType (data) {
  if (data === '') return '';

  let istypeArray = ['Object', 'Number', 'Array', 'Boolean', 'Null', 'Undefined', 'String', 'Symbol', 'Date', 'BigInt', 'Function'];
  let is = Object.prototype.toString.call(data);
  for (let i = 0; i < istypeArray.length; i++)
  {
    if (is.includes(istypeArray[i])) return istypeArray[i]
  }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值