zl程序教程

您现在的位置是:首页 >  后端

当前栏目

js之空值判断

JS 判断 空值
2023-09-11 14:19:18 时间

代码

function isnull(_obj) {
    const _type = Object.prototype.toString.call(_obj).slice(8, -1).toLowerCase()
    let _flag = false
    // 基础类型
    if (["string", "number", "boolean", "undefined", "null"].find(_i => _i === _type)) { if (!_obj) _flag = true }
    // 引用类型
    else if (_type === "array") { if (!_obj.length) _flag = true }
    else if (_type === "object") { if (JSON.stringify(_obj) === "{}") _flag = true }
    // ES6新增类型
    else if (["map", "set"].find(_i => _i === _type)) { if (!_obj.size) _flag = true }
    // 抛出错误
    else throw new Error("isnull不支持判断当前的类型是否为空")
    return _flag
}

解释

  1. 当前代码用于判断一些js数据类型是否为空的
  2. 他可以判断的类型如下
// 字符串(String)、数字(Number)、布尔(Boolean)、对空(Null)、未定义(Undefined) 对象(Object)、数组(Array)NAN 非数字
//  Map 与 Set

拓展

在一些多条件判断的时候,我们除了用 ||或者 &&来连接条件之外,还可以使用everysome,来进行判断,入戏

// 将一系列的条件放到数组中
const _arr = [1 === 3, 3 === 3, 8 == 9]
// 调用相应的方法
console.log(_arr.some(_i => _i)); // true
console.log(_arr.every(_i => _i)); // false

相当于对于一组条件的判断