JavaScript-判空方法

  Java的判断和JavaScript挺不一样的,有时候经常在JavaScript写Java的判空方法挺难受的。下面做个总结

  1. 在Javasciript中,如果只是判断 变量是否为null(这个也是用的比较多的一种方式),直接下面:

let exp = null;
if (!exp)
{
  alert("is null");
}

  2. 如果认为 undified 也属于为空的现象,就可以下面的写法:

if (typeof exp == "undefined" || !exp)
{
  alert("is null");
}

  3. 上面的写法其实还有漏洞的,当 exp=0或false时,会被认为是null,再完善一点可以下面的写法:

var exp = 0;
if (!exp && typeof exp != "undefined" && exp != 0)
{
  alert("is null");
}

   4. 判断json对象是否为空,如下:

   最后还是推荐一个比较常用判断函数,如下:

    function isEmpty(obj) {
        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;
        }
    }
原文地址:https://www.cnblogs.com/ibcdwx/p/15448736.html