zoukankan      html  css  js  c++  java
  • js 判断是否为空对象、空数组

    当需要判断参数是否为空时,总希望 js 能够提供原生的判断方法,可惜并没有,只能自己封装了。

    function isEmpty(obj) {
      // 检验 undefined 和 null
      if(!obj && obj !== 0 && obj !== '') {
               return true;   }
      if(Array.prototype.isPrototypeOf(obj) && obj.length === 0) { 
        return true;
      }
      if(Object.prototype.isPrototypeOf(obj) && Object.keys(obj).length === 0) { 
        return true;   
      }   
      return false;
    }

    isPrototypeOf() 方法用于测试一个对象是否存在于另一个对象的原型链上。即判断 Object 是否存在于 obj 的原型链上。需要注意的是,js 中一切皆是对象,也就是说,Object 也存在于数组的原型链上,因此这里数组需要先于对象检验。

    ps:

    isPrototypeOf 和 instanceof operator 是不一样的。在表达式 object instanceof AFunction 中,检测的是 AFunction.prototype 是否在object 的原型链中,而不是检测 AFunction 自身。

    该方法属于 ES3 标准,现代浏览器均支持,包括 IE。  <( ̄︶ ̄)>

    Object.keys() 方法会返回一个由给定对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和使用 for...in 循环遍历该对象时返回的顺序一致、

    该方法属于 ES5 标准,IE9 以上和其它现代浏览器均支持。如果你很不幸的需要兼容 IE9以下浏览器,那就用 for...in 代替吧。但是,for...in 会将对象原型链上的属性也枚举出来,因此还需要加个判断。

    for(var key in obj) {
    	if(obj.hasOwnProperty(key)) {
    		return false;
    	}
    }
    
    hasOwnProperty()属于 ES3 标准,现代浏览器均支持,包括 IE。可以放心使用啦。  <( ̄︶ ̄)>

    还有一种很特别的检验空对象或空数组的方法,就是使用 JSON.stringify()
    JSON.stringify(obj) === '{}';
    JSON.stringify(obj) === '[]'
  • 相关阅读:
    remove white space from read
    optimize the access speed of django website
    dowload image from requests
    run jupyter from command
    crawl wechat page
    python version 2.7 required which was not found in the registry windows 7
    health
    alternate rows shading using conditional formatting
    word
    【JAVA基础】static 关键字
  • 原文地址:https://www.cnblogs.com/xxhuan/p/6582114.html
Copyright © 2011-2022 走看看