2013-04-09 57 views
-1

我有兩個單獨的if else語句。即使我認爲只有一個是真的,另一個總是被調用,反之亦然。這是兩條if語句總是鏈接,即使它不是真

第一個

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"); 
} 

的,如果(養老金>收入),如果(unionDues>(收入 - 養老金))總是打電話給對方。

提前收到變量收入並且之後的檢查將檢查值是否有效。

如果我的收入是100,而我的養老金是50,我的unionDues是60,我認爲它應該只調用第二個if else語句,但它同時調用兩者。

如果我的收入是1,而我的養老金是2,而我的團費是0,那麼兩個警報都會收到警報。有誰知道我的問題是什麼?

編輯:修復很簡單,我只是parseFloat()的一切,它的工作。

+1

是'pension'和'income'和'unionDues數字?或者他們是絃樂? – jfriend00 2013-04-09 02:28:35

+0

+1,打我吧。是剛剛建議'parseInt'ing他們 – 2013-04-09 02:30:05

+0

所有這些簡單的變量,或者是其中的一些功能?你可能想要console.log()或者另外檢查它們的值是否是你認爲的值。 – sockmonk 2013-04-09 02:30:25

回答

0

首先,您應該確保所有三個值都是數字,而不是字符串,因爲字符串比較不適用於具有不同數字位數的數字。你希望這裏的一切都是實際的數字。如果這些來自用戶輸入數據,那麼您將不得不使用類似parseInt(nnn, 10)的東西將它們轉換爲數字。


然後,一旦它們都是數字,你的邏輯就有一些問題。

如果pension大於income,則兩個else if語句都將爲true。

第一else if是顯而易見的,因爲它是一個直接else if (pension > income),如果養老金是肯定的,那麼它不會匹配第一if

第二個else if (unionDues > (income - pension))將匹配,因爲income - pension將爲負值,這意味着unionDues的任何位置值都將與此條件匹配。


如果你只希望永遠被觸發一個警報,那麼你可以把所有四個條件進入或者使用一個if和三個else if或一些比較其他形式永遠只能選擇一個條件相同的邏輯語句。

另一種可能的解決方案是累積錯誤字符串,如果錯誤字符串在結尾處非空,則顯示一條警報,其中包含所有錯誤條件。


也許你需要的是這隻能說明encoutered的第一個錯誤(如果所有的值是true號):

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"); 
} 
+0

你能想出一個if else語句嗎?它只會針對我想要實現的內容而特定? – user2140629 2013-04-09 02:33:06

+0

@ user2140629 - 我不清楚你想要實現什麼邏輯。我已經爲我的答案添加了一些選項。 – jfriend00 2013-04-09 02:34:26

+0

RRSP貢獻超過收入。 聯盟會費超過收入減去RRSP的貢獻。這些是驗證要求。 RRSP =養老金。這是什麼不應該發生 – user2140629 2013-04-09 02:36:42

0
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"); 
} 
相關問題