两个if语句总是连接在一起,即使它不为真

Two if statements are always linked even if it's not true

本文关键字:在一起 语句 if 连接 两个      更新时间:2023-09-26

我有两个独立的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");
}