js 判断空值null 、““ 、“ “、undefined等

文章提供了一个JavaScript函数`empty(e)`用于检测空值、0、false以及undefined等无效值。它使用switch语句进行判断。此外,还讨论了字符串判断空的方法,如使用trim().length和replace正则匹配。文章强调了在比较时的一些细节和陷阱,例如空字符串与undefined的差异。
部署运行你感兴趣的模型镜像

封装一个方法来判断,包含了空值、0、false 等,适用已定义的变量:(可以用来判断后端返回来的值是否有用)

function empty(e) {
  switch (e) {
    case "":
    case 0:
    case " ":
    case "0":
    case null:
    case false:
    case undefined:
      return true;
    default:
      return false;
  }
}
document.write(empty(" ")) //
document.write("<br>")
document.write(empty(null)) // true
document.write("<br>")
document.write(empty(0)) // true
document.write("<br>")
document.write(empty(7)) // false
document.write("<br>")
document.write(empty("")) // true
document.write("<br>")
document.write(empty((function() {
    return ""
}))) // false

还有一些细节要注意:

" "==undefined
false
""==undefined
false
undefined === undefined
true
null === null
true
Boolean(undefined)
false
Boolean(null)
false
Boolean("")
false
Boolean(" ")
true

null == undefined
true

null === undefined
false

判断字符串是否为空有哪些方法:

1.用trim()去掉左右两边空,再用长度判断:代码为【if (string.trim().length == 0)】;

2、replace正则匹配方法

  去除字符串内所有的空格:str = str.replace(/\s*/g,"");

  去除字符串内两头的空格:str = str.replace(/^\s*|\s*$/g,"");

  去除字符串内左侧的空格:str = str.replace(/^\s*/,"");

  去除字符串内右侧的空格:str = str.replace(/(\s*$)/g,"");

您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值