javascript 使用 JS 反转对象数组的问题

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

Issue Reversing Array of Objects with JS

javascriptobjectreverse

提问by captDaylight

I'm parsing JSON and getting an array of objects with javascript. I've been doing this to then append an element for each object:

我正在解析 JSON 并使用 javascript 获取一组对象。我一直在这样做,然后为每个对象附加一个元素:

for(o in obj){ ... }

But I realized that for a certain situation I want to go backwards through the array. So I tried this before the for loop:

但是我意识到在某些情况下我想倒退数组。所以我在 for 循环之前尝试了这个:

obj = obj.reverse();

However this isn't reversing the order of the objects in the array. I could simply put a count variable in the for loop to manually get the reverse, but I'm puzzled as to why reverse doesn't seem to work with object arrays.

然而,这并没有颠倒数组中对象的顺序。我可以简单地在 for 循环中放置一个计数变量来手动获取反向,但我很困惑为什么反向似乎不适用于对象数组。

回答by Pointy

There's no such thing as an "object array" in JavaScript. There are Objects, and there are Arrays (which, of course, are also Objects). Objects have properties and the properties are not ordered in any defined way.

JavaScript 中没有“对象数组”这样的东西。有对象,也有数组(当然,它们也是对象)。对象具有属性,并且属性没有以任何定义的方式排序。

In other words, if you've got:

换句话说,如果你有:

var obj = { a: 1, b: 2, c: 3 };

there's no guarantee that a for ... inloop will visit the properties in the order "a", "b", "c".

不能保证for ... in循环会按“a”、“b”、“c”的顺序访问属性。

Now, if you've got an array of objectslike:

现在,如果您有一个对象数组,例如:

var arr = [ { a: 1 }, { b: 2 }, { c: 3 } ];

then that's an ordinary array, and you can reverse it. The .reverse()method mutates the array, so you don't re-assign it. If you dohave an array of objects (or a real array of any sort of values), then you should notuse for ... into iterate through it. Use a numeric index.

那么这是一个普通的数组,你可以反转它。该.reverse()方法会改变数组,因此您无需重新分配它。如果你这样做有对象的数组(或任何类型的值的真正的数组),那么你应该使用for ... in来遍历它。使用数字索引。

edit— it's pointed out in a helpful comment that .reverse()does return a reference to the array, so reassigning won't hurt anything.

编辑- 在有用的注释中指出.reverse()它确实返回对数组的引用,因此重新分配不会有任何伤害。

回答by Guffa

That's because the for (o in obj)doesn't iterate the array as an array, but as an object. It iterates the properties in the object, which also includes the members in the array, but they are iterated in order of name, not the order that you placed them in the array.

那是因为for (o in obj)不会将数组作为数组迭代,而是作为对象迭代。它迭代对象中的属性,其中还包括数组中的成员,但它们是按名称的顺序迭代的,而不是您将它们放入数组中的顺序。

Besides, you are using the reversemethod wrong. It reverses the array in place, so don't use the return value:

此外,您使用的reverse方法错误。它原地反转数组,所以不要使用返回值:

obj.reverse();