更新时间: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
是变量.
它为null
,undefined
,0
,000
,""
,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 " "
.