Why does accessing an array element show undefined?

1

Having the following array:

var arrayElementos = ["elemento 1" , "elemento 2" , "elemento 3"];

We apply the length property:

var arrayLargo = arrayElementos.length;

And doing alert(arrayLargo); returns 3.

I try to access the third element and it comes out:

alert (arrayLargo[3]);
undefined 
  

Why, if there are 3 items, can I not access this third party?

    
asked by Victor Alvarado 29.04.2017 в 15:59
source

1 answer

5

This happens because in programming the indexes of arrays start to count always from 0 and not from 1 , that is:

//Número de elementos:     1               2              3    
var arrayElementos = ["elemento 1" , "elemento 2" , "elemento 3"];
//Posición y/o indice:     0               1              2

console.log(arrayElementos[2])

Obviously your fix has 3 elements , but its indices go from the number 0

You can always access the last element of an array by:

//Número de elementos:     1               2              3    
var arrayElementos = ["elemento 1", "elemento 2", "elemento 3"];
//Posición y/o indice:     0               1              2

var length = arrayElementos.length; // 3

//                                    3    - 1 = 2
var ultimoElemento = arrayElementos[length - 1];

console.log(ultimoElemento);
    
answered by 29.04.2017 / 16:06
source