黄舟2017-04-17 11:34:54
Copied from @xelz, but avoiding some of the pitfalls of old JavaScript:
js
let dict = {a: 3, b:1, c:2}; for (let key of Object.keys(dict).sort()) { console.log(key, dict[key]); }
Tested and passed in Firefox 28.
怪我咯2017-04-17 11:34:54
The dictionary is unordered, but there is a default order for traversing the dictionary.
If the subject wants to change the default order of traversing the dictionary, just
function sortDict(dict) {
var dict2 = {},
keys = Object.keys(dict).sort();
for (var i = 0, n = keys.length, key; i < n; ++i) {
key = keys[i];
dict2[key] = dict[key];
}
return dict2;
}
However, this method seems to be invalid for numeric keys. When you need numeric keys, add a prefix (in fact, it is not a real dictionary without a prefix)
Downstairs, please don’t use in
when traversing the array. This kind of error is difficult to find. . .
function sortEach(dict, fn) {
var keys = Object.keys(dict).sort();
for (var i = 0, n = keys.length, key; i < n; ++i) {
key = keys[i];
fn(dict[key], key, dict);
}
}
Thank you Evian, you can still do it:
javascript
for (var key of Object.keys(dict).sort()) { // do something with dict[key] }
阿神2017-04-17 11:34:54
Sorting a dictionary is a false proposition, because the dictionary is 无序
and you cannot change its order
If you want to 有序遍历
it, use
for (var key in Object.keys(dict).sort()) {
// do something with dict[key]
}