如何在JavaScript中检查空字符串/未定义字符串/空字符串? [英] How can I check for an empty/undefined/null string in JavaScript?

查看:82
本文介绍了如何在JavaScript中检查空字符串/未定义字符串/空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了这个问题,但是我没有看到JavaScript特定的示例.在JavaScript中是否有简单的string.Empty可用,还是仅检查""的情况?

I saw this question, but I didn't see a JavaScript specific example. Is there a simple string.Empty available in JavaScript, or is it just a case of checking for ""?

推荐答案

以前的所有答案都不错,但这会更好.使用双重NOT运算符(!!):

All the previous answers are good, but this will be even better. Use dual NOT operators (!!):

if (!!str) {
    // Some code here
}

或使用类型转换:

if (Boolean(str)) {
    // Code here
}

两者都具有相同的功能.将变量转换为布尔型,其中str是变量.
它为nullundefined0000""false返回false.
它为字符串"0"和空格" "返回true.

Both do the same function. Typecast the variable to Boolean, where str is a variable.
It returns false for null, undefined, 0, 000, "", false.
It returns true for string "0" and whitespace " ".

这篇关于如何在JavaScript中检查空字符串/未定义字符串/空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆