Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I can't iterate over a javascript array

I am going crazy here, I have an associative array as seen below which is defined after the page finishes loading. However Array.forEach is returning undefined and I have no idea why. The array is most definitely populated during the loop. Can anyone give me any ideas? Also doesn’t work with JQuery’s $.each

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Arrays are usually a mapping of index (integer >= 0) to value. In your case you’ve treated the array as a dictionary e.g. key (string) to value.

You’ve probably done something like this:

members = new Array();
members['animerox1213'] = 'Ashima';

JavaScript allows this, after all it is still an object:

typeof members === 'object'

But instead of adding a value to the array, you’ve actually set a string property on the object called animerox1213. That is not how an array should be used and we can observe this by checking the size:

members.length === 0;

Consequently forEach does not do anything as it considers it an empty array.

That said, as it is still just an object (with enumerable string properties), it is iterable with for…in:

for (m in members) {
  console.log(m, members[m]);
}

That said, consider using just an object e.g. members = {} or Map. Note especially the section Objects vs. Maps.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading