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

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

封装一个方法来判断,包含了空值、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,"");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值