当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 详解js类型判断

详解js类型判断

2018年05月29日  | 移动技术网IT编程  | 我要评论
js类型转换中typeof会将null也识别为object, 而且返回的类型比少,我们用object.prototype.tostring来实现 第一版 fun

js类型转换中typeof会将null也识别为object, 而且返回的类型比少,我们用object.prototype.tostring来实现

第一版

function isarray(value){
  return object.prototype.tostring.call(value) === "[object array]";
}

function isfunction(value){
  return object.prototype.tostring.call(value) === "[object function]";
}

但是这样写,一个个去判断数组,函数,对象的话很麻烦,比较过程化

第二版

我们想用type(obj)的方式返回对应的类型字符串,因为typeof是小写,所以我们也返回小写的标准

function type(obj){
  // -1 代表截止到倒数一位
  return object.prototype.tostring.call(obj).slice(8,-1).tolowercase()
}

type([]) // "array"

但是这样每次都需要对判断的类型进行slice和tolowercase也是比较耗性能的, 而且判断类型只有几种,所以我们可以用对象提前将可能的结果缓存起来

第三版

//将types放外面 而不是放在type函数里面, 利用闭包,优化性能,不用每次判断都声明一次typess
var types = {
  '[object function]': 'function',
  '[object number]': 'number',
  ...
}

function type(obj) {
  var str = object.prototype.tostring.call(obj)
  return types[str]
}

当然上面的types我们还可以这样优化

// 参考自jquery源码
var types = {}
当然也可以直接用数组存储
"boolean number string function array date regexp object error".split(" ").foreach(function(e,i){
  types [ "[object " + e + "]" ] = e.tolowercase();
}) ;

判断window对象

利用window对象的window属性等于自身

function iswindow( obj ) {
  // obj !== undefined 是为了防止没传参数的时候后面报错
  // uncaught typeerror: cannot read property 'window' of undefined的错误
  
  return obj !== undefined && obj === obj.window;
}

判断是不是dom元素

iselement = function(obj) {
  return !!(obj && obj.nodetype === 1);
}

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网