Loop through associative array in reverse

Four things:

  1. JavaScript has arrays (integer-indexed [see comments below]) and objects (string-indexed). What you would call an associative array in another language is called an object in JS.

  2. You shouldn't use for in to loop through a JS array.

  3. If you're looping through an object, use: hasOwnProperty.

  4. JavaScript doesn't guarantee the order of keys in an object. If you care about order, use an array instead.

If you're using a normal array, do this:

for (var i = arr.length - 1; i >= 0; i--) {
    //do something with arr[i]
}

Warning: this answer is ancient.

If you're here for a quick fix, kindly refer to the much better answer below.

Original answer retained, because reasons. See comments.


Using a temporary array holding the keys in reverse order:

var keys = new Array();

for (var k in arr) {
    keys.unshift(k);
}

for (var c = keys.length, n = 0; n < c; n++) {
   alert(arr[keys[n]]);
}

Tags:

Javascript