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 差不多能判斷了,歡迎加群一起交流入群一起交流


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM