Why my for for-each loop is not iterating over my JavaScript associative array object?
// defining an array
var array = [];
// assigning values to corresponding keys
array["Main"] = "Main page";
array["Guide"] = "Guide page";
array["Articles"] = "Articles page";
array["Forum"] = "Forum board";
// expected: loop over every item,
// yet it logs only "last" assigned value - "Forum"
for (var i = 0; i < array.length; i++) {
console.log(i);
}
EDIT: jQuery each()
could be helpful: https://api.jquery.com/jQuery.each/
associative arrays
in JS: it's either plain Array or an Object. Nothing prevents adding non-numeric properties toArray
, but that doesn't make itassociative
- in particular,length
property won't auto-count these properties. – raina77ow Sep 14 '13 at 17:44