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
>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.
