javascript 检查 null 或空字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50930106/
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
javascript check null or empty string
提问by user3402571
Why is this not possible?
为什么这是不可能的?
var value = null;
if(value == (null || ""))
{
//do something
}
I would like to check a value if it is null or empty without using the variable over and over again.
我想检查一个值是否为空或为空,而无需一遍又一遍地使用该变量。
回答by Ankit Agarwal
Use !value. It works for undefined, nulland even ''value:
使用!value. 它适用于undefined,null甚至''价值:
var value = null;
if(!value)
{
console.log('null value');
}
value = undefined;
if(!value)
{
console.log('undefined value');
}
value = '';
if(!value)
{
console.log('blank value');
}
回答by Some programmer dude
If we split the condition into its two relevant parts, you first have null || "". The result of that will be equal to the empty string "".
如果我们将条件拆分为两个相关部分,您首先拥有null || "". 其结果将等于空字符串""。
Then you have value == ""., which will be falseif valueis null.
那么你有value == "".,false如果value是null。
The correct way to write your condition is value == null || value == "".
写出条件的正确方法是value == null || value == "".

