likes
comments
collection
share

浅谈 JavaScript 数据类型判断

作者站长头像
站长
· 阅读数 14

整理了该系列面试题旨在学会相关知识点,从而轻松应对面试题的各种形式,本文讲解了 JavaScript 中判断数据类型的各种方法。

感觉有帮助的小伙伴请点赞 鼓励一下 ~

typeof 运算符

  • 识别所有值类型;
  • 识别函数类型;
  • 识别引用类型,但是无法区分对象,数组以及 null
  • InfinityNaN 会被识别为 number,尽管 NaNNot-A-Number 的缩写,意思是"不是一个数字"。
  • 我们可以使用 typeof 来检测一个变量是否存在,如 if(typeof a!="undefined"){},而当使用 if(a) 时,如果 a 不存在(未声明), 则会报错。
  let a
  const b = nullconst c = 100const d = 'warbler'
  const e = trueconst f = Symbol('f')
  const foo = () => {}
  const arr = []
  const obj = {}
  console.log(typeof a) //=> undefined
  console.log(typeof b) //=> object
  console.log(typeof c) //=> number
  console.log(typeof d) //=> stringconsole.log(typeof e) //=> boolean
  console.log(typeof f) //=> symbol
  console.log(typeof foo) //=> function
  console.log(typeof arr) //=> object
  console.log(typeof obj) //=> object
  console.log(typeof Infinity) //=> number
  console.log(typeof NaN) //=> number
   

instanceof 方法

  • 用来检测引用数据类型,值类型都会返回 false
  • 左操作数是待检测其类的对象,右操作数是对象的类。如果左侧的对象是右侧的实例,则返回 true否则返回 false
  • 检测所有 new 操作符创建的对象都返回 true
  • 检测 nullundefined 会返回 false
  const foo = () => { }
  const arr = []
  const obj = {}
  const data = new Date()
  const number = new Number(3)
  console.log(foo instanceof Function) //=> true
  console.log(arr instanceof Array) //=> trueconsole.log(obj instanceof Object) //=> trueconsole.log(data instanceof Object) //=> trueconsole.log(number instanceof Object) //=> true
  console.log(null instanceof Object) //=> false
  console.log(undefined instanceof Object) //=> false

constructor 方法

  • 除了 undefinednull 之外,其他类型都可以通过 constructor 属性来判断类型。
   const c = 100
  const d = 'warbler'
  const e = trueconst f = Symbol('f')
  const reg = /^[a-zA-Z]{5,20}$/
  const foo = () => { }
  const arr = []
  const obj = {}
  const date = new Date();
  const error = new Error();
  console.log(c.constructor === Number) //=> true
  console.log(d.constructor === String) //=> true
  console.log(e.constructor === Boolean) //=> true
  console.log(f.constructor === Symbol) //=> true
  console.log(reg.constructor === RegExp) //=> true
  console.log(foo.constructor === Function) //=> true
  console.log(arr.constructor === Array) //=> true
  console.log(obj.constructor === Object) //=> true
  console.log(date.constructor === Date) //=> true
  console.log(error.constructor === Error) //=> true

Object.prototype.toString.call

  • 对于 Object.prototype.toString() 方法,会返回一个形如 [object XXX] 的字符串。
  • 使用Object.prototype.toString.call 的方式来判断一个变量的类型是最准确的方法。
  • Object.prototype.toString.call 换成 Object.prototype.toString.apply 也可以。
let a
  const b = null
  const c = 100
  const d = 'warbler'
  const e = true
  const f = Symbol('f')
  const reg = /^[a-zA-Z]{5,20}$/
  const foo = () => { }
  const arr = []
  const obj = {}
  const date = new Date();
  const error = new Error();
  const args = (function() {
    return arguments;
  })()
  console.log(Object.prototype.toString.call(a)) //=> [object Undefined]
  console.log(Object.prototype.toString.call(b)) //=> [object Null]
  console.log(Object.prototype.toString.call(c)) //=> [object Number]
  console.log(Object.prototype.toString.call(d)) //=> [object String]
  console.log(Object.prototype.toString.call(e)) //=> [object Boolean]
  console.log(Object.prototype.toString.call(f)) //=> [object Symbol]
  console.log(Object.prototype.toString.call(reg)) //=> [object RegExp]
  console.log(Object.prototype.toString.call(foo)) //=> [object Function]
  console.log(Object.prototype.toString.call(arr)) //=> [object Array]
  console.log(Object.prototype.toString.call(obj)) //=> [object Object]
  console.log(Object.prototype.toString.call(date)) //=> [object Date]
  console.log(Object.prototype.toString.call(error)) //=> [object Error]
  console.log(Object.prototype.toString.call(args)) //=> [object Arguments]

封装成简单的函数使用

const getPrototype = (item) => Object.prototype.toString.call(item).split(' ')[1].replace(']', '');
console.log(getPrototype('abc')) //=> String

空值 null

我们还可以通过下面的方法来判断变量是否为 null 。

  let exp = null;
  if (!exp && typeof (exp) !== "undefined" && exp !== 0) {
    console.log('exp is null');
  }
  if (exp === null) {
    console.log('exp is null');
  }
  if (!exp && typeof exp === "object") {
    console.log('exp is null');
  }
  

未定义 undefined

我们还可以通过下面的种方法来判断变量是否为 undefined 。

  let exp;
  if (exp === void 0) {
    console.log('exp is undefined');
  }

数字

我们还可以通过下面的方法来判断变量是否为 数字

  let exp = 100;
  // isNaN 检查不严密 如果 exp 是一个空串或是一个空格,isNaN 是会做为数字 0 进行处理的
  if (!isNaN(exp)) {
    console.log('exp is number');
  }
  // 利用正则判断字符串是否为 0-9let reg = /^[0-9]+.?[0-9]*/
  if (reg.test(exp)) {
    console.log('exp is number');
  }
  if (parseFloat(exp).toString() !== 'NaN') {
    console.log('exp is number');
  }
  

数组

我们还可以通过下面的方法来判断变量是否为 数组

  let exp = [];
  if (Array.isArray(exp)) {
    console.log('exp is Array');
  }