JavaScript foreach loop on an associative array object

Why is my for for-each loop 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(array[i]);
}

jQuery each() could be helpful: https://api.jquery.com/jQuery.each/

10 Answers
10

Leave a Comment