Array problem in javascript

3

I am trying to use the contents of a variable as the name of an Array, but it is 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, instead of appearing "apple".

Why does this happen?

    
asked by anonymous 28.04.2015 / 20:06

1 answer

2

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

var palavra = "carro";

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

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

That is, you are getting positions of your string , not your array. You can store everything in a multidimensional array. The first index will be the name of your variable, and the second index will be a copy of the 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];
    
28.04.2015 / 20:21