zoukankan      html  css  js  c++  java
  • 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 差不多能判断了

  • 相关阅读:
    Postman提取接口返回值设置变量
    Python-浅拷贝与深拷贝
    Python列表
    typeorm查询两个没有关联关系的实体
    springboot去掉数据源自动加载
    docker搭建redis集群
    实习工作记录(一)大文件上传vue+WebUploader
    js重点之promise
    css重点
    git简单命令整理
  • 原文地址:https://www.cnblogs.com/dengxiaoning/p/13412200.html
Copyright © 2011-2022 走看看