How to use foreach in Javascript associative array

Asked

Viewed 490 times

3

I am seeing here that the length of an associative array in JS is reset.. As I access these 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 catch anything... How do I access?

  • Try for (var key in myArray) {
 var value = myArray[key];
 console.log(key, value);
}

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);

3

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

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);

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 the .push() which does just that, add elements at the end of the array, or the .unshift() which 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 you can use foreach to iterate the array.

Browser other questions tagged

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