JS基础面试题:判断数据类型方法

本文探讨了JavaScript中的typeof运算符在判断数据类型上的优缺点,指出其对原始类型和引用类型的处理,以及instanceof方法和Object.prototype.toString.call()的使用场景和局限性。
摘要由CSDN通过智能技术生成

typeof

优点:快速区分基本数据类型
缺点:不能将Object、Array和Null区分,都返回object

  1. typeof的作用?
    区分数据类型,可以返回7种数据类型:number、string、boolean、undefined、object、function ,以及 ES6 新增的 symbol
  2. typeof 能正确区分数据类型吗?
    不能。对于原始类型,除 null 都可以正确判断;对于引用类型,除 function 外,都会返回 object
  3. typeof 注意事项
  • typeof 返回值为 string 格式,注意类似这种考题: typeof(typeof(undefined)) -> “string”
  • typeof 未定义的变量不会报错,返回 “undefiend”
  • typeof(null) -> “object”: 遗留已久的 bug
  • typeof无法区别数组与普通对象: typeof([]) -> “object”
  • typeof(NaN) -> “number”

instanceof

优点:能够区分Array、Object和Function,适合用于判断自定义的类实例对象
缺点:Number,Boolean,String基本数据类型不能判断

  1. instanceof 判断对象的原型链上是否存在构造函数的原型。只能判断引用类型。
  2. instanceof 常用来判断 A 是否为 B 的实例

Object.prototype.toString.call()

优点:精准判断数据类型
缺点:写法繁琐不容易记,推荐进行封装后使用

toString.call(()=>{})       // [object Function]
toString.call({})           // [object Object]
toString.call([])           // [object Array]
toString.call('')           // [object String]
toString.call(22)           // [object Number]
toString.call(undefined)    // [object undefined]
toString.call(null)         // [object null]
toString.call(new Date)     // [object Date]
toString.call(Math)         // [object Math]
toString.call(window)       // [object Window]
  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值