聊一下关于判断数据类型

159 阅读2分钟
  1. 思路

首先整理下js中我们经常碰到的一些数据类型判断的方法typeofinstanceofconstructorprototype

  1. 区别
  1. typeof操作符返回一个字符串,表示未经计算的操作数的类型。选自MDN
console.log(typeof 2)     =====> number
console.log(typeof '1')   =====> string
console.log(typeof false) =====> boolean
console.log(typeof [])    =====> object
console.log(typeof {})    =====> object
console.log(typeof null)  =====> object
console.log(typeof undefined) => undefined
console.log(typeof function(){}) function
console.log(typeof new Date() => object
  • 关于数组和对象判断都是object。他是未经过操作数的类型
  • JavaScript 最初的实现中,JavaScript 中的值是由一个表示类型的标签和实际数据值表示的。对象的类型标签是 0。由于 null 代表的是空指针(大多数平台下值为 0x00),因此,null的类型标签也成为了 0,typeof null就错误的返回了"object"
  1. instance 所述instanceof操作者测试的存在constructor.prototype在object的原型链。选自MDN
console.log([] instanceof Array)        ---------------> true
console.log(new Date() instanceof Date) ------------> true
console.log(function(){} instanceof Function) ------------> true
console.log(function(){} instanceof function) ------------> false
  • 很有意思的一个判断方法就是[]根据onject和array判断的时候都为true.{} instanceof Array的答案是false.所以如果有幸自己封装判断数据类型这类且方法应该不错。

3.出自阮一峰老师的javascript教程 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]。
<!-- 函数的实例 -->
var type = function (o){
  var s = Object.prototype.toString.call(o);
  return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};