js判断常见的数据类型判断

8次阅读

共计 2138 个字符,预计需要花费 6 分钟才能阅读完成。

JS7 种基本数据类型

  • 六种基本数据类型:String, Number, Boolean, Null, undefined, symbol
  • 一种引用类型:Object

1. 使用 js 判断数据类型方法

常见的判断方法有

  1. typeof
  2. instanceof
  3. Object.prototype.toString
  4. constructor
  5. duck type

1.1 typeof 运算符(常见)

typeof 是一种较常见的判断方法,返回的是一个字符串,比较特殊之处在判断 Null 类型数据,返回'object'

let a = 'abc'
let b = 123
let c = true
let d = null
let e = undefined
let f = Symbol('abc')
console.log('类型 a:', typeof a)
console.log('类型 b:', typeof b)
console.log('类型 c:', typeof c)
console.log('类型 d:', typeof d)
console.log('类型 e:', typeof e)
console.log('类型 f:', typeof f)


复杂类型 Object,可以判断function,其他array、object 等会判断为 object

如果要判断数组类型,就可以用下面的instanceof

1.2 instanceof(只适用对象类型判断)

用法:

object instanceof constructor

object表示需要判断的对象,constructor表示某个构造函数,instanceof运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。

let a = []
let b = function () {}
let c = new String()
let d = new Number()
console.log(a instanceof Array)
console.log(b instanceof Function)
console.log(c instanceof String)
console.log(c instanceof Object)
console.log(d instanceof Number)
console.log(d instanceof Object)

  • 需要注意的是,String、Number、Date等对象也是属 object,所以同理,若手写了一个Car 类,那么判断结果就是即属于 Car 类,又属于object
function Car(brand, money) {
  this.brand = brand
  this.money = money
}
var mycar = new Car("特斯拉", "30w")
console.log(mycar instanceof Car)
console.log(mycar instanceof Object)

1.3 Object.prototype.toString(较推荐使用)

这里将 call()替换成 apply()也是一样的效果,

let a = []
let b = function () {}
let c = new String()
let d = new Number()
let e = null
let f = {}
console.log('类型 a:', Object.prototype.toString.call(a))
console.log('类型 b:', Object.prototype.toString.call(b))
console.log('类型 c:', Object.prototype.toString.call(c))
console.log('类型 d:', Object.prototype.toString.call(d))
console.log('类型 e:', Object.prototype.toString.call(e))
console.log('类型 f:', Object.prototype.toString.call(f))

1.4 constructor

let a = []
let b = function () {}
let c = new String()
let d = new Number()
let e = {}
let f = null
console.log(a.constructor === Array)
console.log(b.constructor === Function)
console.log(c.constructor === String)
console.log(c.constructor === Object)
console.log(d.constructor === Number)
console.log(d.constructor === Object)
console.log(e.constructor === Object)
console.log(f.constructor) // 报错


null 是无效对象,当然不存在 constructor,这节内容强烈推荐阮大大的文章 prototype 对象

1.5 duck type

与其说 duck type(鸭子类型)是种判断方法,不如是种编程思想,比如不知道一个对象是不是数组,可以判断它的 length 是不是数字,它是不是有 join,push 这样的一些数组的方法的等等,通过一些特征判断对象是否属于某些类型

正文完
 0