判断JavaScript的数据类型的三种方式

1.typeof

typeof方法可以判断除了null以外的所有的基础数据类型以及function。

    console.log(typeof 1)         // number
    console.log(typeof 'hello')   // string
    console.log(typeof undefined) // undefined
    console.log(typeof true)      // boolean
    console.log(typeof Symbol())  // symbol
    console.log(typeof null)      // object
    console.log(typeof function () { }) // function
    console.log(typeof {})        // object
    console.log(typeof [])        // object

2.instanceof

typeof方法可以判断复杂数据类型,不能判断所有的基础数据类型。

    console.log(1 instanceof Number)          // false
    console.log('hello' instanceof String)    // false
    console.log(true instanceof Boolean)      // false
    console.log(Symbol() instanceof Symbol)   // false
    console.log({} instanceof Object)         // true
    console.log([] instanceof Array)          // true
    console.log(function () { } instanceof Function) // true
    console.log(null instanceof Null)         // 报错
    console.log(undefined instanceof Undefined) // 报错

3.Object.prototype.toString

Object.prototype.toString方法可以判断所有的数据类型,需要配合call()使用。

    console.log(Object.prototype.toString.call(1))         // [object Number]
    console.log(Object.prototype.toString.call('hello'))   // [object String]
    console.log(Object.prototype.toString.call(true))      // [object Boolean]
    console.log(Object.prototype.toString.call(Symbol()))  // [object Symbol]
    console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
    console.log(Object.prototype.toString.call(null))      // [object Null]
    console.log(Object.prototype.toString.call({}))        // [object Object]
    console.log(Object.prototype.toString.call([]))        // [object Array]
    console.log(Object.prototype.toString.call(function () { })) // [object Function]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值