I'm trying to make a function that takes the value of x
, where x
is the position. For example:
- 1 = gold
- 2 = silver
- 3 = bronze
And that in the other positions it is 0 or any number after 3 says "nothing". This is the code I have:
var array = ["oro", "plata", "bronce"]
function medallaSegunPuesto(x) {
for (var i = 0; i < array.length; i++) {
if (i == (x - 1)) {
return array[i];
} else {
return "nada";
}
}
}
console.log(medallaSegunPuesto(3));
The problem is that when I put the else
it doesn't recognize position 2 or 3. Any suggestions?
You don't need a loop. It simply checks that the value is in the indicated range, otherwise it returns "nothing". Something like that:
It seems to me that it is even simpler using the logical or
||
.Although you already have correct solutions (and better than using a loop). I'm going to put the root of the problem (although I imagine you already know it) and a possible solution (although it would be easier and more efficient to choose another answer).
The problem is in the
if...else
, which returns values in both theif
and theelse
. That means that if the value is 1 it will return "gold", but for any other value, it will go into itelse
and return "nothing" without even checking the rest of the indices.To fix this you could remove the
else
and move thereturn "nada"
just after the loopfor
:Again, this solution is not the best or quick way to solve the problem. But it could be useful if instead of iterating an array you were iterating over the indices of an object (although there are surely better solutions in that case as well).