Problem with javascript array

Asked

Viewed 78 times

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?

  • 1

    Is this in the global scope? If you are, you can use window[nomeArray][posicaoArray].

  • 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.

  • @Rafaelwithoeft worked! thank you very much, helped a lot.

  • 1

    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.

1 answer

2

What you are trying to do is wrong, the displayed result is totally predictable. Imagine the following variable:

var palavra = "carro";

In Javascript, everything is an object, so we can take parts of the word normally using an array. To get the letter "c", we use the index 0, since it is the first. Example:

var palavra = "carro";
document.body.innerHTML += palavra[0];

I mean, you’re taking positions from your string, not your array. You can store everything in a multidimensional array. The first index shall be the name of its variable, and the index shall be a copy of the other array. Example:

var posicaoArray = 2;
var nomeArray = "frutas";
var frutas = new Array();
frutas [0] = "Banana";
frutas [1] = "Melancia";
frutas [2] = "Maçã";
frutas [3] = "Laranja";

var data = {};
data[nomeArray] = frutas;

document.body.innerHTML += data[nomeArray][posicaoArray];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.