js 判断数据是否为空

 

先来回顾下js 的8大
基础类型:
Number、String、Boolean、Null、undefined、object、symbol、bigInt。

引用类型:
Object 、Array、Function、 Date

而js 也是一个类型自由的语言,定义一个变量可以赋值任何类型,然鹅这给开发也会带来一些麻烦,如对一个数据进行为空校验:

  1. JSON判断:
    /**
     * Checked if it is json object
     * Note: If it is a json, its format must be '{"name":"dex"}' or {"name":"dex"}
     * @param {Object} tragetObj
     */
    function _isJSON(tragetObj) {
      if (typeof (tragetObj) === 'string') {
        try {
          var obj = JSON.parse(tragetObj)
          if (typeof (obj) === 'object' && obj) {
            return true
          } else {
            return false
          }
        } catch (e) {
          return false
        }
      } else if (typeof (tragetObj) === 'object' && !Array.isArray(tragetObj)) {
        return true
      } else {
        return false
      }
    }

 

  1. 数据为空验证:
       /**
     * Check if it is empty
     * and return true if it is
     * @param {Object} checkObj
     */
   function isEmpty(checkObj) {
      if (!checkObj || !checkObj.length) { // Checke if it is ""、 undefined、 null 、NaN、 []
        return true
      } else {
        if (_isJSON(checkObj)) { // check object
          let hasKey = ''
          if (typeof (checkObj) === 'string') {
            checkObj = JSON.parse(checkObj)
          }

          for (const key in checkObj) {
            hasKey = key
            break
          }

          if (!hasKey) {
            return true
          } else {
            return false
          }
        } else {
            if(checkObj === 'undefined' || checkObj === 'null'){
                return true
            }
          return false
        }
      }
    }

 

ok 差不多能判断了,欢迎加群一起交流入群一起交流

posted @ 2020-07-31 11:45  奔跑的痕迹  阅读(3741)  评论(0编辑  收藏  举报