How to use forEach in associative JavaScript array

3

I'm seeing here that the length of an associative array in JS gets zeroed. How do I access those values then?

Example:

let myArray = [];

myArray['zero'] = 0;
myArray['um'] = 1;
myArray['dois'] = 2;

console.log(myArray.length);

If I want to give a forEach for example, I can not because it does not get anything ... How do I log in?

    
asked by anonymous 29.11.2018 / 14:58

3 answers

3

Only with Object is it possible to associate.

let myArray  = {};

myArray.zero = 0;
myArray.um   = 1;
myArray.dois = 2;

console.log(Object.keys(myArray ).length);

Or

let myArray  = {};
let myArray  = {
   um: 1,
   dois: 2,
   tres: 3
};

console.log(Object.keys(myArray ).length);
    
29.11.2018 / 15:01
3

You need to use objects to be included in the array, you can mount them and use the push() function to get into the array.

It would look like this:

let myArray = [];

myArray.push({'zero': 0})
myArray.push({'um': 1})
myArray.push({'dois': 2})

for(var i in myArray) {
    console.log(i)
}

//Descomente para ver o resultado final do array
//console.log(myArray);
    
29.11.2018 / 15:03
3

In other languages like PHP for example it is normal to use myArray[] = 0; to add elements to an array.

In JavaScript the [] is to access properties. So if you want the same effect you can use .push() that does this, add elements at the end of the array, or .unshift() that adds at the beginning of the array.

const myArray = [];

myArray.push({'zero': 0})
myArray.push({'um': 1})
myArray.push({'dois': 2})

console.log(myArray.length);
console.log(JSON.stringify(myArray));

Using the array so you can use forEach to iterate through the array.

    
29.11.2018 / 15:33