Javascript 这个 if 语句不应该检测到 0;只有空或空字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3887816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
This if statement should not detect 0; only null or empty strings
提问by Hamster
Using JavaScript, how do I NOT detect 0, but otherwise detect null or empty strings?
使用 JavaScript,如何不检测 0,而是检测空字符串或空字符串?
回答by Quentin
If you want to detect all falsey values except zero:
如果要检测除零以外的所有假值:
if (!foo && foo !== 0)
So this will detect null
, empty strings, false
, undefined
, etc.
因此,这将检测null
、 空字符串false
、undefined
、 等。
回答by BoltClock
From your question title:
从你的问题标题:
if( val === null || val == "" )
I can only see that you forgot a =
when attempting to strict-equality-compare val
with the empty string:
我只能看到您=
在尝试val
与空字符串进行严格相等比较时忘记了 a :
if( val === null || val === "" )
Testing with Firebug:
使用 Firebug 进行测试:
>>> 0 === null || 0 == ""
true
>>> 0 === null || 0 === ""
false
EDIT:see CMS's comment instead for the explanation.
编辑:有关解释,请参阅 CMS 的评论。
回答by ArtBIT
function isNullOrEmptyString(val) {
return (val === null || val === '');
}
console.log({
"isNullOrEmptyString(0)": isNullOrEmptyString(0),
"isNullOrEmptyString('')": isNullOrEmptyString(""),
"isNullOrEmptyString(null)": isNullOrEmptyString(null),
"isNullOrEmptyString('something')": isNullOrEmptyString("something"),
});
回答by Ahmed Sobhy
I know this might be a too late answer but it might help someone else.
我知道这可能是一个为时已晚的答案,但它可能会帮助其他人。
If I understand you correctly you want the below statement to exclude the 0:
如果我理解正确,您希望以下语句排除 0:
if(!value) {
//Do things
}
I think the easiest way to do this is to write the statement like this:
我认为最简单的方法是编写这样的语句:
if(!value && value !== 0) {
//Do things
}
I hope this helps.
我希望这有帮助。