Js数据类型判断都有哪几种方式?它们的区别是什么?

  1. typeof判断
    typeof返回的类型都是字符串形式
alert(typeof "helloworld")    // "string"     
alert(typeof 123)             // "number"
alert(typeof new Function())  // "function"
alert(typeof Symbol())        // "symbol"
alert(typeof true)            // "true"
alert(typeof undefined)       // "undefined"
alert(typeof 'undefined')     // "string"
alert(typeof null)            // "object"
alert(typeof [1,2,3])         // "object"
alert(typeof new Date())      // "object"
alert(typeof new RegExp())    // "object"

  1. Constructor
    实例constructor属性指向构造函数本身
    constructor 判断方法跟instanceof相似,但是constructor检测Object与instanceof不一样,constructor还可以处理基本数据类型的检测,不仅仅是对象类型

  2. Instanceof
    instanceof可以判类型是否是实例的构造函数
    instanceof 后面一定要是对象类型,并且大小写不能错,该方法适合一些条件选择或分支。

[1,2,3] instanceof Array                // true
new Date() instanceof Date              // true
new Function() instanceof Function      // true
new Function() instanceof function      // false
null instanceof Object                  // false

  1. Object.prototype.toString.call()
    判断类型的原型对象是否在某个对象的原型链上
 console.log(Object.prototype.toString.call("123"))           // [object String]
 console.log(Object.prototype.toString.call(123))             // [object Number]
 console.log(Object.prototype.toString.call(true))            // [object Boolean]
 console.log(Object.prototype.toString.call([1, 2, 3]))       // [object Array]
 console.log(Object.prototype.toString.call(null))            // [object Null]
 console.log(Object.prototype.toString.call(undefined))       // [object Undefined]
 console.log(Object.prototype.toString.call({name: 'Hello'})) // [object Object]
 console.log(Object.prototype.toString.call(function () {}))  // [object Function]
 console.log(Object.prototype.toString.call(new Date()))      // [object Date]
 console.log(Object.prototype.toString.call(/\d/))            // [object RegExp]
 console.log(Object.prototype.toString.call(Symbol()))        // [object Symbol]

  1. 通过object原型上的方法判断
    比如array.isArray()来判断是不是一个数组

  2. ===(严格运算符)
    通常出现在我们的条件判断中,用来判断数据类型的话就会非常的有局限性,比如判断一个变量是否为空,变量是否为数据等

二、typeof与instanceof区别

  • typeof会返回一个变量的基本类型,instanceof返回的是一个布尔值
  • instanceof 可以准确地判断复杂引用数据类型,但是不能正确判断基础数据类型
  • 而typeof 也存在弊端,它虽然可以判断基础数据类型(null 除外),但是引用数据类型中,除了function 类型以外,其他的也无法判断
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值