简体   繁体   中英

JavaScript or Node.js unexpectedly sort objects

When I running this code by 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? I don't want this.

What you're seeing is a behavior of the V8 JavaScript engine. It's not something specified by the JavaScript specification, and it's not something you can rely on (most engines don't do that ).

But the important thing here is: There is no order to a JavaScript object. So V8's behavior is just as correct as putting those keys in any other order. If you want things in a particular order, you have to use an ordered container, like an array.

JavaScript objects aren't ordered. 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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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