Hello @Raphael, it seems to me that your exercise aims to make you understand two things.
- That the indexes have their beginning in
0
.
- Identify/Work with the size of a
Array
.
Array.length
I see the first you ever killed,
as it is placing as the first element of its Array the string "nada"
So for you to finish your exercise just you do the checking (if
) using the array size (posicoes.length
).
Important detail, posicoes.length
is the amount of elements in your Array posicoes
, is not the index of the last element.
Knowing this just add to the check if( numero >= posicoes.length ) return "nada";
var posicoes = ["nada", "ouro", "prata", "bronze"];
function medalhaDeAcordoComPosto(numero){
if( numero >= posicoes.length ) return "nada";
return posicoes[numero];
}
console.log(0,medalhaDeAcordoComPosto(0));
console.log(1,medalhaDeAcordoComPosto(1));
console.log(2,medalhaDeAcordoComPosto(2));
console.log(3,medalhaDeAcordoComPosto(3));
console.log(4,medalhaDeAcordoComPosto(4));
console.log(5,medalhaDeAcordoComPosto(5));
console.log(15,medalhaDeAcordoComPosto(15));
Note: You may need to add if
a check for negative numbers, leaving +/- like this: if( numero >= posicoes.length || numero < 0)
Now let’s use the index 0
In this other example we will create an array only with prizes, so we will have:
var posicoes = ["ouro", "prata", "bronze"];
In your job we’ll do the following:
- Diminish
1
in the reported value.
That way if the person calls the function by passing the 1
he will treat as 0
.
Make a if
to verify:
- if the value is less than
0
, that is, negative index and invalidity.
- Or if the value is greater than to amount of elements in the array
- 1
, that is, the last index of the array. (posicoes.length-1)
var posicoes = ["ouro", "prata", "bronze"];
function medalhaDeAcordoComPosto(numero){
numero -= 1; /// ; isso é a msm coisa que `numero = numero - 1;`
if( numero < 0 || numero > posicoes.length-1 ) return "nada";
return posicoes[numero];
}
console.log(0,medalhaDeAcordoComPosto(0));
console.log(1,medalhaDeAcordoComPosto(1));
console.log(2,medalhaDeAcordoComPosto(2));
console.log(3,medalhaDeAcordoComPosto(3));
console.log(4,medalhaDeAcordoComPosto(4));
console.log(5,medalhaDeAcordoComPosto(5));
console.log(15,medalhaDeAcordoComPosto(15));
Actually, Undefined returns yes.
– G. Bittencourt
I created a snippet with the code you posted and when you run it you will see the return
undefined
, contradicting the text of your question. This will require you to edit the question and elaborate a [mcve] that demonstrates the behavior you are describing.– Woss