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:
javascriptfor (var key of Object.keys(dict).sort()) {
// do something with dict[key]
}
Copied from @xelz, but avoiding some of the pitfalls of old JavaScript:
Tested and passed in Firefox 28.
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
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. . .Thank you Evian, you can still do it:
Sorting a dictionary is a false proposition, because the dictionary is
无序
and you cannot change its orderIf you want to
有序遍历
it, use