两个if语句总是连接在一起,即使它不为真
Two if statements are always linked even if it's not true
我有两个独立的if else语句。即使我认为只有一个是正确的,另一个总是被调用,反之亦然。在这里
第一个
if (pension < 0 ) {
alert("Pension value error. Try again.");
}
else if (pension > income) {
alert("RRSP Contribution cannot exceed the income.");
}
第二个
if (unionDues < 0 ) {
alert("Union dues value error. Try again.");
}
else if (unionDues > (income - pension)) {
alert("Union dues cannot exceed the income less the RRSP contribution");
}
if(pension> income)和if(union会费> (income - pension))总是互相调用。
变量收入是在手之前提示的,之后的检查是检查值是否有效。
如果我的收入是100,我的养老金是50,我的union会费是60,我认为它应该只调用第二个If else语句,但它调用了两个。
如果我的收入是1,我的养老金是2,我的union会费是0,这两个警报也会被提醒。有人知道我的问题是什么吗?
编辑:修复很简单,我只是parseFloat()的一切,它的工作。
首先,您应该确保所有三个值都是数字,而不是字符串,因为字符串比较对于具有不同位数的数字不能正常工作。你希望这里的每一项都是一个实际的数字。如果这些来自用户输入的数据,那么您必须使用parseInt(nnn, 10)
之类的东西将它们转换为数字。
那么,一旦它们都是数字,你的逻辑就有问题了。
如果pension
大于income
,则else if
的两个表述都为真。
第一个else if
是明显的,因为它是一个直接的else if (pension > income)
,如果养老金是正的,那么它将不匹配第一个if
。
第二个else if (unionDues > (income - pension))
将匹配,因为income - pension
将是负的,这意味着unionDues
的任何位置值都将匹配此条件。
如果您只希望触发一个警报,那么您可以使用一个if
和三个else if
或其他形式的只选择一个条件的比较将所有四个条件放入同一个逻辑语句中。
另一种可能的解决方案是累积错误字符串,如果错误字符串最后不为空,则显示一个包含所有错误条件的警报。
也许你所需要的只是显示遇到的第一个错误(如果你所有的值都是真数):
if (pension < 0 ) {
alert("Pension value error. Try again.");
} else if (pension > income) {
alert("RRSP Contribution cannot exceed the income.");
} else if (unionDues < 0 ) {
alert("Union dues value error. Try again.");
} else if (unionDues > (income - pension)) {
alert("Union dues cannot exceed the income less the RRSP contribution");
}
if (pension < 0) {
alert("Pension value error. Try again.");
}
else if (unionDues < 0) {
alert("Union dues value error. Try again.");
}
else if (pension > income) {
alert("RRSP Contribution cannot exceed the income.");
}
else if (unionDues > (income - pension)) {
alert("Union dues cannot exceed the income less the RRSP contribution");
}
- 将依赖外部库的UMD模块与browserfy捆绑在一起
- 函数在return语句之前返回空对象
- 在if语句下的html中使用javascript变量
- 如何使在文本字段中输入的值显示在HTML语句中
- 如何将具有相同功能的两个select html标签的两个JS组合在一起
- 在if语句中,undefined等于false
- 在if语句注释的条件内指定变量的值
- jade/pug是否可以在include语句中使用变量
- 将3个函数合并在一起
- 使用javascript将两个输入的日期添加在一起
- XSLT在IF语句后添加图书价格
- 避免将lib依赖项与webpack+handlebas加载程序捆绑在一起
- PHP、Javascript和SQL代码混杂在一起
- 有没有办法把它们串在一起,这样它们基本上可以同时工作
- if语句混合在一起
- 将“if/then.else”语句与“switch”语句组合在一起
- Jison:当if-else和for语句结合在一起时,语法冲突
- 是否可以在switch语句中将字符串和整数值一起传递给case ?
- 两个if语句总是连接在一起,即使它不为真
- 我如何结合2 RegEx语句在一起,使用JavaScript/RegEx