Javascript 你一般怎么判断数据类型?

关于数据类型的判断,这里我们主要讨论typeof,instanceof,Object.prototype.toString这三种方法

1.typeof

  • a.原始类型:数值、字符串、布尔值分别返回number、string、boolean。
  • b.函数返回function。
  • c.undefined返回undefined。
  • d.其他情况都返回object(window,null,{},[])

 因此,使用typeof可以判断原始类型数据的类型,但对于对象(进一步区别数组,对象等)就有局限性了

2.instanceof

instanceof运算符返回一个布尔值,表示某个对象是否为指定的构造函数的实例。

因此可以用来判断对象是否是构造函数的示例对象,即用来判断详细数据类型,但是对于原始数据类型无效。

3.Object.prototype.toString

toString方法的作用是返回一个对象的字符串形式,默认情况下返回类型字符串。

Object.prototype.toString.call(value)

  • 数值:返回[object Number]。
  • 字符串:返回[object String]。
  • 布尔值:返回[object Boolean]。
  • undefined:返回[object Undefined]。
  • null:返回[object Null]。
  • 数组:返回[object Array]。
  • arguments对象:返回[object Arguments]。
  • 函数:返回[object Function]。
  • Error对象:返回[object Error]。
  • Date对象:返回[object Date]。
  • RegExp对象:返回[object RegExp]。
  • 其他对象:返回[object Object]。

可以用toString封装一个判断数据类型比typeof更精准的函数:

const type = obj => {
  const s = Object.prototype.toString.call(obj);
  return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};

猜你喜欢

转载自blog.csdn.net/josavion/article/details/78839928