简体   繁体   English

反向循环关联数组

[英]Loop through associative array in reverse

I'm using a javascript associative array (arr) and am using this method to loop through it.我正在使用 javascript 关联数组 (arr) 并使用此方法循环遍历它。

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?有没有办法做到这一点?

Four things:四件事:

  1. JavaScript has arrays (integer-indexed [see comments below]) and objects (string-indexed). JavaScript 有数组(整数索引 [见下面的评论])和对象(字符串索引)。 What you would call an associative array in another language is called an object in JS.在另一种语言中你称之为关联数组的东西在 JS 中被称为对象。

  2. You shouldn't use for in to loop through a JS array .不应该使用for in循环遍历 JS 数组

  3. If you're looping through an object, use: hasOwnProperty .如果您正在遍历一个对象,请使用: hasOwnProperty

  4. JavaScript doesn't guarantee the order of keys in an object. JavaScript 不保证对象中键的顺序。 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.这比“for”循环快。

http://blogs.oracle.com/greimer/entry/best_way_to_code_a 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.在现代浏览器中,您现在可以使用Object.keys来获取属性数组并以相反的顺序逐步遍历它,从而跳过初步的密钥收集循环。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM