简体   繁体   English

JavaScript或Node.js意外地对对象进行排序

[英]JavaScript or Node.js unexpectedly sort objects

When I running this code by node app.js 当我通过node app.js运行此代码时

'use strict';

var data = {"456":"First","789":"Second","123":"Third"};

console.log(data);

I've geting next result: 我得到下一个结果:

{ '123': 'Third', '456': 'First', '789': 'Second' }

Why JS or Node.js (I don't know who) sort this object by keys? 为什么JS或Node.js(我不知道是谁)按键对该对象排序? I don't want this. 我不要这个

What you're seeing is a behavior of the V8 JavaScript engine. 您所看到的是V8 JavaScript引擎的行为。 It's not something specified by the JavaScript specification, and it's not something you can rely on (most engines don't do that ). 这不是JavaScript规范所指定的内容,也不是您可以依赖的内容(大多数引擎都不那样做 )。

But the important thing here is: There is no order to a JavaScript object. 但是这里重要的是:JavaScript对象没有顺序 So V8's behavior is just as correct as putting those keys in any other order. 因此,V8的行为与将这些键按任何其他顺序放置一样正确。 If you want things in a particular order, you have to use an ordered container, like an array. 如果要按特定顺序排列事物,则必须使用有序容器,例如数组。

JavaScript objects aren't ordered. JavaScript对象未排序。 If you want things in order, you can use an array. 如果您想按顺序排列,可以使用数组。

var data = [
    { key: "456", value: "First" },
    …
];

Or, alternatively, keep the key order in a separate array. 或者,也可以将键顺序保留在单独的数组中。

Properties in an object aren't ordered. 对象中的属性未排序。 You can't expect the order you give to be preserved when a representation of your object is built for the console. 当为控制台构建对象的表示形式时,您不能期望保留给定的顺序。

The iteration order is implementation dependent. 迭代顺序取决于实现。 Don't rely on it. 不要依赖它 If you need some order, use another data structure (for example and array of key-values). 如果需要某种顺序,请使用其他数据结构(例如,键值数组)。

// try this to sort employees by age //尝试按年龄对员工进行排序

employees.sort(function(a, b){
 return a.age-b.age
});

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

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