javascript “未定义”出现在警报中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5017616/
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
'undefined' appearing in alert
提问by user517406
I am using Javascript to validate some code, and it works fine, but whenever I call alert to show the errors, at the beginning of the alert message I get 'undefined'. So when I should expect the alert to show 'Please enter a Low Target', instead I get 'undefinedPlease enter a Low Target'. Can somebody tell me what is wrong with my code?
我正在使用 Javascript 来验证一些代码,并且它工作正常,但是每当我调用警报来显示错误时,在警报消息的开头我都会收到“未定义”。因此,当我期望警报显示“请输入低目标”时,我得到的是“未定义请输入低目标”。有人可以告诉我我的代码有什么问题吗?
//validation
var lowTarget;
var highTarget;
var errorList;
var isValid = true;
lowTarget = $('input[name="txtLowTarget"]').val();
highTarget = $('input[name="txtHighTarget"]').val();
if (lowTarget == "") {
errorList += "Please enter a Low Target\n";
isValid = false;
}
else {
if (isNumeric(lowTarget) == false) {
errorList += "Low Target must be numeric\n";
isValid = false;
}
}
if (highTarget == "") {
errorList += "Please enter a High Target\n";
isValid = false;
}
else {
if (isNumeric(highTarget) == false) {
errorList += "High Target must be numeric\n";
isValid = false;
}
}
if (isValid == true) {
if (!(parseFloat(highTarget) > parseFloat(lowTarget))) {
errorList += "High Target must be higher than Low Target\n";
isValid = false;
}
}
if (isValid == false) {
alert(errorList);
}
回答by Nikita Rybak
Assign some default value to errorList, e.g. empty string
为 分配一些默认值errorList,例如空字符串
var errorList = "";
Until you do that, initial value of errorListis undefined.
直到你做到这一点,初始值errorList就是undefined。
回答by safeer008
I was finding the same problem in my project while using
我在使用时在我的项目中发现了同样的问题
var try2 = document.getElementsByName("y_email").value;
alert(try2);
Now I used the following and it works well
现在我使用了以下内容并且效果很好
var try2 = document.getElementsByName("y_email")[0].value;
alert(try2);
(So Be doubly sure that what you are using in correct format to use.)
(所以要加倍确保您使用的格式正确。)

