When executing the code, the result always prints the statement of else
, even if the condition is if
true.
function Calculate()
{
var planetsList = {
"Mercurio": 0,
"Venus": 0,
"Tierra": 1,
"Marte": 2,
"Júpiter": 16,
"Saturno": 17,
"Urano": 14,
"Neptuno": 2,
"Plutón": 1
}
var num = document.form.elements["number"].value;
var res = "";
for(var planet in planetsList) {
if(num <= planetsList[planet]) {
res += planet + ": " + planetsList[planet] + "<br/>";
}
else {
res = "No hay planetas que contengan una cantidad de satélites igual o mayor a la especificada.";
}
}
document.getElementById("result").innerHTML = res;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Objetos</title>
</head>
<body>
<div>
<form name="form" method="post">
<table>
<tr>
<th>Ingrese el número de satélites:</th>
<td><input type="text" size="2" name="number" /></td>
</tr>
<tr>
<td colspan="2"><input type="button" value="Calcular" onclick="Calculate()"/></td>
</tr>
</table>
</form>
</div>
<div id="result"></div>
</body>
</html>
I think your condition is wrong. As I see it is true for some elements of your array but you override the final response when a single element does not meet the condition.
It should move your validation outside of the
for
and only return the "no planets..." message if the response is still empty at the end of yourfor
There is a little problem in the logic when building the html string to display.
In effect, the planets are being listed, but since the loop goes through the entire array, at some point it comes across a planet that does not comply and in that line of code the entire content of the string is replaced. The result is that at the end of the loop, only the message that there are no planets that meet the condition is displayed, except in the case that the last one in the array does.
the solution is to condition the loop, if there were no planets previously it is written, otherwise it is skipped.