问题
var input = [1,1,2,3,10,5,3,4],
stat = {},
temp = [];
input.forEach(function(v) {
stat[v] = 1;
});
for (v in stat) {
temp.push(v);
}
console.log(temp); //["1", "2", "3", "4", "5", "10"]
How does the "sorting" occur?
Edit:
Made cross-browser screenshots (see comment) and a jsPerf.
回答1:
The "sorting" occurs in for(v in stat). As per ECMA script standard, the order in which the keys are fetched is up to the vendor, and some browser vendors obviously chose to fetch all keys in sorted order. You shouldn't rely on this kind of "sorting" being "implemented in all browsers".
回答2:
Clearly not a rule:
var input = ["c", "b", "a"],
stat = {},
temp = [];
input.forEach(function(v) {
stat[v] = 1;
});
for (v in stat) {
temp.push(v);
}
console.log(temp); //["c", "b", "a"]
I'm guessing the sorting only happens for integer keys so that iterating over an object is consistent with iterating over an array. (Or that it's because objects and arrays are internally the same.)
回答3:
Items get pushed to the temp array in the order they are retrieved from the stat object, but you don't get to decide what order is that.
You can't sort key value pairs of js Objects at your will.
来源:https://stackoverflow.com/questions/21405567/find-unique-and-sort-does-the-latter-only-happen-or-is-it-by-ecma