javascript 检查一个值是否为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10389991/
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
Check if a value is null?
提问by Wilson
In javascript, I want to have an if else statement that will change an elements value(a text field in an html form) to zero if nothing is typed in. I had the following:
在 javascript 中,我想要一个 if else 语句,如果没有输入任何内容,它会将元素值(html 表单中的文本字段)更改为零。我有以下内容:
if(document.getElementById('dollarinput').value == null){
var dollars = 0;
}
else{
var dollars = parseInt(document.getElementById('dollarinput').value);
}
Something isn't working correctly in the if condition, but I'm not sure what I did wrong.
在 if 条件下有些东西不能正常工作,但我不确定我做错了什么。
回答by mattytommo
You need to move the variable declaration above the if
and check for empty quotes, like so:
您需要将变量声明移到 上方if
并检查空引号,如下所示:
var dollars;
if(document.getElementById('dollarinput').value == ''){
dollars = 0;
}
else{
dollars = parseInt(document.getElementById('dollarinput').value);
}
回答by Jeff Hines
var dollars = 0;
var dollarinput = document.getElementById('dollarinput');
if( ! dollarinput.length )
{
dollars = parseInt(dollarinput.value);
}
回答by bfavaretto
Check if it's an empty string instead:
检查它是否为空字符串:
if(document.getElementById('dollarinput').value == ''){
var dollars = 0;
} else{
var dollars = parseInt(document.getElementById('dollarinput').value, 10);
}
回答by gdoron is supporting Monica
- Value of an input can never be
null
! if there is no value, it will be an empty string. alert('' == null);?? // false
- 输入的值永远不可能是
null
! 如果没有值,它将是一个空字符串。 alert('' == null);?? // false
Fixed code:
固定代码:
if(document.getElementById('dollarinput').value){
var dollars = 0;
}
else{
var dollars = parseInt(document.getElementById('dollarinput').value);
}