Javascript之常见类型判断汇总

基本类型的判断

typeof

typeof操作符返回一个字符串,表示未经计算的操作数的类型,其返回结果对比如下

1234567
UndefinedNullBooleanNumberStringObjectSymbol
undefinedObjectbooleannumberstringobjectsymbol
Object下还有细分类型为:ArrayDateRegExpError

需要注意的是以上的返回值都为小写的字符串

Object.prototype.toString

Object.prototype.toString能够检测出基本数据类型,及Object下细分类型,其返回形式是[object typeClass];例如:

console.log(Object.prototype.toString.call(undefined)) // [object Undefined]

此方法基本能够检测出所有类型了

类型判断

var classtype = {};

"Boolean Number String Function Array Date RegExp Object Error Symbol Set Map".split(" ").map(function(item) {
    classtype["[object " + item + "]"] = item.toLowerCase();
})

function type(obj) {
  // 解决IE6下null和undefined会被Object.prototype.toString识别成[object Object]
  if (obj == null) {
      return obj + "";
  }

  //当typeof判断出类型为object|functin时调用Object.prototype.toString.call方法
  return typeof obj === "object" || typeof obj === "function" ?
      classtype[Object.prototype.toString.call(obj)] || "object" :
      typeof obj;
}

空对象的判断

对于一下对象按照空对象null,undefind,[],空字符串,true or false,{},number类型,new Preson()构造函数

jQuery实现

for循环一旦执行,则判断为非空属性

function isEmptyObject( obj ) {
  var name;
  // for in 方法是可以遍历原型链的……
  for ( name in obj ) {
      return false;
  }
  return true;
}

lodash实现

function isEmpty(value) {
  if (value == null) {
    return true;
  }
  // 判断类数组,如果length等于0,则说明是空的类数组
  if (isArrayLike(value) &&
      (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
        isBuffer(value) || isTypedArray(value) || isArguments(value))) {
    return !value.length;
  }
  var tag = getTag(value);
  if (tag == mapTag || tag == setTag) {
    return !value.size;
  }
  // 判断value 是否是一个原型对象
  if (isPrototype(value)) {
    return !baseKeys(value).length;
  }
  for (var key in value) {
    //对象中存在key且不是原型链里的
    if (hasOwnProperty.call(value, key)) {
      return false;
    }
  }
  return true;
}

数组判断

当检测Array实例时, Array.isArray 优于 instanceof,因为Array.isArray能检测iframes

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

类数组判断

定义

所谓类数组就是指含有指向对象的数字索引下标,及length属性标志个数,类数组不含有push、concat等数组的方法

条件如下:

  • 是数组
  • length有,且必须为数字
  • length-1必须存在,这是为了检测数组最后一个值是否存在

常见的类数组:arguments,document.querySelectAll()等获取dom的方法

实现

function likeArray(obj) {
  // obj必须存在且含有lenght属性
  var length = !!obj && 'length' in obj && obj.length,
  // 获取obj的数据类型
    type = type(obj)
  // 不能是function类型,不能是window
  // 如果是array则直接返回true
  // 或者当length的数据类型是number,且大于0,存在最后一个属性
  return 'function' !== type && !isWindow(obj) && 
  ('array' === type || length === 0 || (typeof length === 'number' && length > 0 && (length - 1) in obj))
}

注:

length === 0认为是数组,是为了判断如下情况:

function test(){
  console.log(likeArray(arguments))
}
test()

underscore的实现

underscore对类数组的实现比较简单宽松,其判断依据是:`length为数字,且取值范围在0<=length<=MAX_ARRAY_INDEX

//js 中能精确表示的最大数字
var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
var getLength = property('length');
var isArrayLike = function(collection) {
  var length = getLength(collection);
  return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
};

NaN的判断

NaN的产生:当算术运算返回一个未定义的或无法表示的值时,NaN就产生了。但是,NaN并不一定用于表示某些值超出表示范围的情况。将某些不能强制转换为数值的非数值转换为数值的时候,也会得到NaN。

判断一个数是不是NaN不能单纯地使用 === 这样来判断, 因为NaN不与任何数相等, 包括自身

//loadsh的实现
function isNaN(value) {
  return isNumber(value) && value != +value;
}

DOM元素判断

//loadsh的实现
function isObjectLike(value) {
  return value != null && typeof value == 'object';
}
function isElement(value) {
  return isObjectLike(value) && value.nodeType === 1
}

window对象判断

判断依据:window对象又一个window属性指向自身,及window === window.windowMDNopen in new window

function isWindow( obj ) {
  return obj != null && obj === obj.window;
}
小红包免费领
小礼物走一走
Last Updated:
Contributors: slbyml
部分内容来源于网络,如有侵权,请留言或联系994917123@qq.com;访问量:waiting;访客数:waiting