我可以以相反的顺序循环遍历 javascript 对象吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18977881/
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
Can I loop through a javascript object in reverse order?
提问by frequent
So I have a JavaScript object like this:
所以我有一个这样的 JavaScript 对象:
foo = {
"one": "some",
"two": "thing",
"three": "else"
};
I can loop this like:
我可以像这样循环:
for (var i in foo) {
if (foo.hasOwnProperty(i)) {
// do something
}
}
Which will loop through the properties in the order of one
> two
> three
.
这将按one
> two
>的顺序循环遍历属性three
。
However sometimes I need to go through in reverse order, so I would like to do the same loop, but three
> two
> one
.
但是有时我需要以相反的顺序进行,所以我想做同样的循环,但是three
>> two
> one
。
Question:
Is there an "object-reverse" function. If it was an Array, I could reverse or build a new array with unshift
but I'm lost with what to do with an object, when I need to reverse-loop it's properties. Any ideas?
问题:
是否有“对象反向”功能。如果它是一个数组,我可以反转或构建一个新数组,unshift
但是当我需要反转它的属性时,我不知道如何处理一个对象。有任何想法吗?
Thanks!
谢谢!
采纳答案by Tibos
Javascript objects don't have a guaranteed inherent order, so there doesn't exist a "reverse" order.
Javascript 对象没有保证的固有顺序,因此不存在“反向”顺序。
4.3.3 Object An object is a member of the type Object. It is an unordered collectionof properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.
4.3.3 对象对象是对象类型的成员。它是一个无序的属性集合,每个属性都包含一个原始值、对象或函数。存储在对象属性中的函数称为方法。
Browsers do seem to return the properties in the same order they were added to the object, but since this is not standard, you probably shouldn't rely on this behavior.
浏览器似乎确实按照它们添加到对象的相同顺序返回属性,但是由于这不是标准的,您可能不应该依赖这种行为。
A simple function that calls a function for each property in reverse order as that given by the browser's for..in, is this:
一个简单的函数以与浏览器的 for..in 给出的顺序相反的顺序为每个属性调用一个函数,是这样的:
// f is a function that has the obj as 'this' and the property name as first parameter
function reverseForIn(obj, f) {
var arr = [];
for (var key in obj) {
// add hasOwnPropertyCheck if needed
arr.push(key);
}
for (var i=arr.length-1; i>=0; i--) {
f.call(obj, arr[i]);
}
}
//usage
reverseForIn(obj, function(key){ console.log('KEY:', key, 'VALUE:', this[key]); });
Working JsBin: http://jsbin.com/aPoBAbE/1/edit
工作 JsBin:http://jsbin.com/aPoBAbE/1/edit
Again i say that the order of for..in is not guaranteed, so the reverse order is not guaranteed. Use with caution!
我再说一次 for..in 的顺序是不保证的,所以不保证相反的顺序。谨慎使用!
回答by Maged Mohamed
Why there is no one has mentioned Object.keys()
?
为什么没有人提到Object.keys()
?
you can get Arrayof Object's properties ordered as it is, then you can reverse it or filter it as you want with Array methods .
您可以获得按原样排序的对象属性数组,然后您可以使用 Array 方法根据需要反转或过滤它。
let foo = {
"one": "some",
"two": "thing",
"three": "else"
};
// Get REVERSED Array of Propirties
let properties = Object.keys(foo).reverse();
// "three"
// "two"
// "one"
// Then you could use .forEach / .map
properties.forEach(prop => console.log(`PropertyName: ${prop}, its Value: ${foo[prop]}`));
// PropertyName: three, its Value: else
// PropertyName: two, its Value: thing
// PropertyName: one, its Value: some
回答by ctay
There is no way to loop through an object backwards, but if you recreate the object in reverse order then you are golden! Be cautions however, there is nothing that says the order of the object will stay the same as it changes and so this may lead to some interesting outcome, but for the most part it works...
没有办法向后遍历对象,但是如果您以相反的顺序重新创建对象,那么您就是金子!但是请注意,没有任何内容表明对象的顺序会随着它的变化而保持不变,因此这可能会导致一些有趣的结果,但在大多数情况下它是有效的......
function ReverseObject(Obj){
var TempArr = [];
var NewObj = [];
for (var Key in Obj){
TempArr.push(Key);
}
for (var i = TempArr.length-1; i >= 0; i--){
NewObj[TempArr[i]] = [];
}
return NewObj;
}
The just do the swap on your object like this-
只需像这样对您的对象进行交换-
MyObject = ReverseObject(MyObject);
The loop would then look like this-
然后循环看起来像这样 -
for (var KeysAreNowBackwards in MyObject){
alert(MyObject[KeysAreNowBackwards]);
}
回答by Lorien Brune
This answer is similar to a couple of the others, but some users might find the code below easier to copy-paste for their own uses:
这个答案与其他几个相似,但有些用户可能会发现下面的代码更容易复制粘贴供他们自己使用:
Object.keys(foo).reverse().forEach(function(key) { console.log(foo[key]) });
For an object "foo" as described in the question, this code will output the object elements in reverse order: "else", "thing", "some"
对于问题中描述的对象“foo”,此代码将以相反的顺序输出对象元素:“else”、“thing”、“some”
回答by Mike Tromba
Just use Object.keys()
只需使用 Object.keys()
This function will take care of it for you:
此功能将为您处理:
function loopObject(obj, reverse, logic){
let keys = reverse? Object.keys(obj).reverse() : Object.keys(obj)
for(let i=0;i<keys.length;i++){
logic(obj[keys[i]])
}
}
Example object:
示例对象:
let my_object = {
one: 'one',
two: 'two',
three: 'three'
}
Loop in order:
按顺序循环:
loopObject(my_object, false, val => {
console.log(val) // Insert your logic here.
})
// "one"
// "two"
// "three"
Loop in reverse:
反向循环:
loopObject(my_object, true, val => {
console.log(val) // Insert your logic here.
})
// "three"
// "two"
// "one"