JavaScript for in 循环,但反过来?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9762402/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:45:14  来源:igfitidea点击:

JavaScript for in loop, but in reverse?

javascriptfor-loop

提问by Hyman

Taking a JavaScript object with 4 properties:

使用具有 4 个属性的 JavaScript 对象:

function Object() {
  this.prop1;
  this.prop2;
  this.prop3;
  this.prop4;
}

var obj = new Object();

I use a for(in) loop to inspect each property since I don't know the number or name of the properties:

我使用 for(in) 循环来检查每个属性,因为我不知道属性的数量或名称:

for(property in obj) {
  var prop = obj[property];
}

However I would like to process the properties starting with the last (prop4 in this example). I suppose I would like a reverse-for-in-loop.

但是我想处理从最后一个开始的属性(在这个例子中是prop4)。我想我想要一个反向循环。

How can I do this?

我怎样才能做到这一点?

Thanks, Hyman

谢谢,Hyman

Adding: The object I am referring to is the one returned from JSON.parse. The properties seem to be consistently ordered. There is no keys() method.

添加:我所指的对象是从 JSON.parse 返回的对象。这些属性似乎是一致排序的。没有 keys() 方法。

回答by jfriend00

A for (x in y)does not process the properties in any specific order so you cannot count on any desired order.

Afor (x in y)不以任何特定顺序处理属性,因此您不能指望任何所需的顺序。

If you need to process the properties in a specific order, you will need to get all the properties into an array, sort the array appropriately and then use those keys in the desired order.

如果需要按特定顺序处理属性,则需要将所有属性放入一个数组中,对数组进行适当排序,然后按所需顺序使用这些键。

Using ES5 (or an ES5 shim), you can get all properties into an array with:

使用 ES5(或 ES5 垫片),您可以将所有属性放入一个数组中:

var keys = Object.keys(obj);

You could then sort them either in standard lexical order or sort with your own custom function:

然后,您可以按标准词汇顺序对它们进行排序,也可以使用您自己的自定义函数进行排序:

keys.sort(fn);

And, then you could access them in your desired order:

然后,您可以按照您想要的顺序访问它们:

for (var i = 0; i < keys.length; i++) {
    // process obj[keys[i]]
}

回答by vol7ron

Arrays are ordered objects. Properties in objects are inherently unordered. However, if you have some specific reason that you want to work from back to front of whatever the for..inconstruct would have produced, you could do:

数组是有序的对象。对象中的属性本质上是无序的。但是,如果您有某些特定原因想要从后到前处理for..in构造将产生的任何内容,您可以执行以下操作:

var arr = [];
for (prop in obj) {
   arr.push(prop);
}

for (var n=arr.length; n--; ){
   var prop = obj[arr[n]];
}

回答by dwerner

The ECMAScript standard does not define an order to iteration for for inloops. You will want an array, if your datatypes are to be sorted.

ECMAScript 标准没有定义for in循环的迭代顺序。如果要对数据类型进行排序,则需要一个数组。