开发者

Loop through associative array in reverse

开发者 https://www.devze.com 2023-02-10 04:50 出处:网络
I\'m using a javascript associative array (arr) and am using this method to loop through it. for(var i in 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 开发者_如何学Cthe 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?


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


For a normal array, I would have done this:

var i = arr.length;
while (i--) {
    var value = arr[i];
    alert(i =") "+ value);
}

This is faster than a "for" loop.

http://blogs.oracle.com/greimer/entry/best_way_to_code_a


In modern browsers you can now use Object.keys to get your array of properties and step through it in reverse order, allowing you to skip the preliminary key collection loop.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

var keys = Object.keys(subject);
for (var i = keys.length-1; i >= 0; i--) {
    var k = keys[i],
        v = subject[k];
    console.log(k+":",v);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消