简体   繁体   中英

why wont my else if statement work? (the if and else work, but not the if else statement even though condition is met)

I cannot get the if else statement to work, the if statement and the else statement works,
I test the if else statement with an input of 115 , it doesnt work,
but if i put 135 the if statement works as it should.
I need help to fix the if else statement please!!

 var start = button.addEventListener("click", function() { var lbs = input.value - 45 /*weight without the bar*/ var add = 0 var plates45 = 0 var plates35 = 0 while (lbs.= add) { if ((add += 90) <= lbs) { plates45 += 2 add += 90 forty:innerHTML = "45lbs. " + plates45 } else if ((add += 70) <= lbs) { plates35 += 2 add += 70 thirty:innerHTML = "35lbs: " + plates35 } else { add = lbs /*to prevent infinte loop*/ } } })
 <h1 id="header">Plate Helper</h1> <div id="container1"> <p id="weight">Weight</p> <input type="text" id="input"> </div> <div id="blue"> <button id="button">Calculate</button> </div> <div id="container2"> <center> <p id="result">Plates Needed</p> <div id="forty"> <p id="forty_plate">45lbs: </p> </div> <div id="thirty"> <p id="thirty_plate">35lbs: </p> </div> <div id="twenty"> <p id="twenty_plate">25lbs: </p> </div> <div id="ten"> <p id="ten_plate">10lbs: </p> </div> <div id="five"> <p id="five_plate">5lbs: </p> </div> <div id="two"> <p id="two_plate">2.5lbs: </p> </div> </center>

I refresh the page before each test so i dont think the first if statement affects the condition for the if else statement

The reason it doesn't work is the += operator in the if statements. The first one if ((add += 90) <= lbs){ first adds 90 to add , then checks if add is less than lbs. Then when it arrives at if ((add += 70) <= lbs){ , add is already 90, so then it adds 70 (=160) and checks if it's less than lbs. The solution therefore would be to only add the amount (70 or 90) if the condition is true (ie replace += in if ((add +=... to + but leave the lines within the blocks the qay they are).

As a side note, an alternative way to break out of your loop in the else clause would be the break keyword.

Ps You come from a Python background?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM