3
I’m trying to use the contents of a variable as an array name, but it’s returning a letter of the contents of that variable.
Example:
var posicaoArray = 2;
var nomeArray = "frutas";
var frutas = new Array();
frutas [0] = "Banana";
frutas [1] = "Melancia";
frutas [2] = "Maçã";
frutas [3] = "Laranja";
document.write(nomeArray[posicaoArray]);
It will return the letter " u ", letter number 2 of the word "fruit" if we count from 0, to instead of appearing "apple".
Why does this happen?
Is this in the global scope? If you are, you can use
window[nomeArray][posicaoArray]
.– bfavaretto
I tested it here and it worked:
console.log(eval(nomeArray)[posicaoArray]);
. I don’t know if it’s the best way, but it’s an alternative.– Rafael Withoeft
@Rafaelwithoeft worked! thank you very much, helped a lot.
– Jhonny Rubio Dos Santos
In this case, I believe that for study purposes, there is no problem using the
eval()
, but it is important to read several articles about it (including several I have just read), so that never use it in the wrong way or in ways that compromise its application.– Rafael Withoeft