Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
153
rated 0 times [  154] [ 1]  / answers: 1 / hits: 23461  / 14 Years ago, thu, february 10, 2011, 12:00:00

I'm using a javascript associative array (arr) and am using this method to loop through it.



for(var i in arr) {
var value = arr[i];
alert(i =) + value);
}


The problem is that the order of the items is important to me, and it needs to loop through from last to first, rather than first to last as it currently does.



Is there a way to do this?


More From » javascript

 Answers
1

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]]);
}

[#93799] Wednesday, February 9, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trinityr

Total Points: 49
Total Questions: 107
Total Answers: 96

Location: Mayotte
Member since Fri, Oct 1, 2021
3 Years ago
;