且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在JavaScript中检查空字符串/未定义字符串/空字符串?

更新时间:2022-11-08 07:54:05

以前的所有答案都不错,但这会更好.使用双重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 " ".