Loop through associative array in reverse

前端 未结 4 1668
陌清茗
陌清茗 2020-12-14 08:37

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 =\") \"+         


        
相关标签:
4条回答
  • 2020-12-14 09:23

    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]
    }
    
    0 讨论(0)
  • 2020-12-14 09:31

    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]]);
    }
    
    0 讨论(0)
  • 2020-12-14 09:33

    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

    0 讨论(0)
  • 2020-12-14 09:36

    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 讨论(0)
提交回复
热议问题