Javascript 中的数据类型判断

本系列经过阅读 underscore 源码与实战进而体验函数式编程的思想, 而非经过冗长的文字教程, 细读精度
约 1500 行的 underscore 有利于写出耦合度低, 符合函数式编程思想的代码, 而且能够学到 call 与 apply 执行效率的不一样进而进行代码性能优化的技巧等.javascript

欢迎你们 star 或者 watch 本系列, 您的关注是做者的最大动力, 让咱们一块儿持续进步.
本系列仓库: github.com/zhangxiang9…html

Typeof

咱们都使用 typeof 是用来判断数据类型的命令, 在常规的场景中足以应付数据类型判断的需求:java

var obj = {
   name: 'zhangxiang'
};

function foo() {
    console.log('this is a function');
}

var arr = [1,2,3];

console.log(typeof 1);  // number
console.log(typeof '1');  //string
console.log(typeof true);  //boolean
console.log(typeof null); //object
console.log(typeof undefined); //undefined
console.log(typeof obj); //object
console.log(typeof foo);  //function
console.log(typeof arr);   //object复制代码

能够看到, typeof 命令能够判断全部 javascript 中的基本数据类型(Null, Undefined, Boolean, String, Number), 虽然 null 使用 typeof 返回的是 object 字符串, 可是无碍
它的基本使用, 可是在一些复杂的场景好比 object 与 null, array 与 object, function 与 object 等等的类型区分, typeof 就会显得心有余力不足了.
因此通常来讲, typeof 会使用在比较简单的场景, 好比你几乎能够肯定数据是哪一类数据而后稍微加以区分的时候.举个简单的例子来讲明状况:node

function unique(array){
  var hash = {};
  var result = [], key;
  array.forEach(function(item, index){
    key = item;
    if(typeof item === 'string') {
      key = '_' + item;
    }
    if(!hash[key]) {
      result.push(item);
    } else {
      hash[key] = true;
    }
  });
  return result;
}复制代码

instanceof

instanceof 其实适合用于判断自定义的类实例对象, 而不是用来判断原生的数据类型, 举个例子:git

// a.html
<script>
  var a = [1,2,3];
</script>复制代码
//main.html
<iframe src="a.html"></iframe>

<script>
  var frame = window.frame[0];
  var a = frame.a;
  console.log(a instanceof Array);  // false
  console.log(a.contructor === Array);  //false
  console.log(a instanceof frame.Array); // true
</script>复制代码

是什么缘由致使上面的结果呢? 其实 iframe 之间不会共享原型链, 由于他们有独立的执行环境, 因此 frame a 中的数组 a 不会是本执行环境的实例对象. 经过特性嗅探一样不靠谱, 像经过 contructor
sort, slice 等等的特有的数组(或者其余数据类型)方法或属性, 万一对象中也有 sort, slice 属性, 就会发生误判. 因此最靠谱的方法是使用 Object.prototype.toString 方法.github

Object.prototype.toString

使用 Object.prototype.toString 方法, 能够获取到变量的准确的类型.编程

function foo(){};

Object.prototype.toString.call(1);  '[object Number]'
Object.prototype.toString.call('1'); '[object String]'
Object.prototype.toString.call(NaN); '[object Number]'
Object.prototype.toString.call(foo);  '[object Function]'
Object.prototype.toString.call([1,2,3]); '[object Array]'
Object.prototype.toString.call(undefined); '[object Undefined]'
Object.prototype.toString.call(null); '[object Null]'
Object.prototype.toString.call(true); '[object Boolean]'
....复制代码

Object.prototype.toString 的原理是当调用的时候, 就取值内部的 [[Class]] 属性值, 而后拼接成 '[object ' + [[Class]] + ']' 这样的字符串并返回. 而后咱们使用 call 方法来获取任何值的数据类型.数组

有用的数据类型判断函数

isArray polyfill

isArray 是数组类型内置的数据类型判断函数, 可是会有兼容性问题, 因此模拟 underscore 中的写法以下:浏览器

isArray = Array.isArray || function(array){
  return Object.prototype.toString.call(array) === '[object Array]';
}复制代码

isNaN polyfill

判断一个数是否是 NaN 不能单纯地使用 === 这样来判断, 由于 NaN 不与任何数相等, 包括自身, 因此:性能优化

isNaN: function(value){
  return isNumber(value) && isNaN(value);
}复制代码

这里的 isNumber 就是用上面所说的 Object.prototype.toString 进行判断的, 而后使用 isNaN 来判断值, 至于为何须要在判断 isNaN 以前须要判断是否是 Number 类型, 这是由于 NaN 自己
也是数字类型(Object.prototype.toString 可知), 在 ES6 的 isNaN 中只有值为数字类型使用 NaN 才会返回 true, 这是为了模拟 ES6 的 isNaN.

判断是不是 DOM 元素

在实际项目里面, 有时或许咱们须要判断是不是 DOM 元素对象, 那么在判断的时候利用的是 DOM 对象特有的 nodeType 属性:

isElement: function(obj){
  return !!(obj && obj.nodeType === 1);
}复制代码

判断是不是对象

isObject: function(obj){
  var type = typeof obj;
  return type === 'function' || typeof === 'object' && obj !== null;
}复制代码

这里的对象是狭义的, 是一般所指的 key-value 型的集合, 或者是 function 函数而且不为 null.

判断是不是 arguments 对象 polyfill

判断一个对象是否是 arguments 对象能够经过 Object.prototype.toString 来判断, 可是低版本的浏览器不支持, 他们返回的是 [object Object], 因此须要兼容:

isArguments: function(obj){
  return Object.prototype.toString.call(obj) === '[object Arguments]' || (obj != null && Object.hasOwnProperty.call(obj, 'callee'));
}复制代码

兼容作法原理是经过对象的 hasOwnProperty 方法来判断对象是否拥有 callee 属性从而判断是否是 arguments 对象.

若是以为有收获, 请到 github 给做者一个 star 表示支持吧, 谢谢你们.
本系列仓库: github.com/zhangxiang9…

相关文章
相关标签/搜索