循环遍历关联数组
问题描述:
我正在使用javascript关联数组(arr)并使用此方法循环遍历它。
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?
答
使用按相反顺序按住键的临时数组:
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]]);
}