How to access the contents of an associative array that is inside another array?

4

I'm trying to create an array of arrays where the arrays inside are associative arrays but I do not know how to access them. This is my code.

			var meses = {enero:31, febrero:29, marzo:31}
			var año = [];
			año.push(meses);
			console.log(año[meses.enero])

This way it turns out that January is not defined. Does anyone know how to access?

    
asked by user9333 17.06.2016 в 20:30
source

3 answers

3

Arrays only work with indexes. Each element of an array has an index that goes from 0 to n-1 , where n is the number of elements.

When you do:

año[meses.enero]

You're actually saying:

año[31]

Why? Well, it's simple. Months is a object and in JavaScript the objects function as a key-value structure . The expression meses.enero translates to: Bring me the value of the key jan .

The correct way is:

  var meses = {enero:31, febrero:29, marzo:31}
  var año = [];
  año.push(meses);
  console.log(año[0].enero);

Where año[0] refers to the first (and only) element of the year array.

PD: Try not to use non-English compatible characters to avoid text encoding problems.

    
answered by 17.06.2016 / 20:38
source
0

Actually you are not accessing a array that is inside another array , but to an object that is within a array . Associative arrays take the form:

var tabla = new Array();  
tabla['indice1'] = 'valor1';  //esto ya lo puedes meter en otro array
    
answered by 11.01.2018 в 16:21
0

First let me tell you that as far as I understand you can not declare a variable with a ñ , nor can you go through the ñ , but here I leave it An example of the code you request.

Eye: The Arrays can not be associative as you are thinking, only the Objects.

//Declaramos un Objeto, este si puede ser asociativo.
var meses = {"enero":31,"febrero":28,"marzo":31};
//Declaramos un Arreglo, este NO puede ser asociativo
var anos = [];
//Agregamos al array anos los valores del objeto asociativo
anos.push(meses);
//Sacamos por consola el resultado
console.log(anos);
    
answered by 17.06.2016 в 20:35