Find unique and sort, does the latter only happen or is it by ECMA?

。_饼干妹妹 提交于 2019-12-10 12:13:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!