Javascript 反向循环关联数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4956256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop through associative array in reverse
提问by Urbycoz
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?
有没有办法做到这一点?
采纳答案by Linus Kleen
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]]);
}
回答by Skilldrick
Four things:
四件事:
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.
If you're looping through an object, use:
hasOwnProperty
.JavaScript doesn't guarantee the order of keys in an object. If you care about order, use an array instead.
JavaScript 有数组(整数索引 [见下面的评论])和对象(字符串索引)。在另一种语言中你称之为关联数组的东西在 JS 中被称为对象。
如果您要遍历对象,请使用:
hasOwnProperty
。JavaScript 不保证对象中键的顺序。如果您关心顺序,请改用数组。
If you're using a normal array, do this:
如果您使用的是普通数组,请执行以下操作:
for (var i = arr.length - 1; i >= 0; i--) {
//do something with arr[i]
}
回答by Mark Schultheiss
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”循环快。
回答by Ben Thielker
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);
}