0

可能重复:
按键排序 JavaScript 对象

{
    "0": 3900,
    "1": 42,
    "10": 135,
    "2": 5,
    "3": 20,
    "4": 33,
    "5": 24,
    "6": 35,
    "7": 56,
    "8": 60,
    "9": 147
}

如何根据键整数类型对 javascript 键进行排序。对于上述给定的输入,最终输出的格式应为

{
0: 39,
1: 42,  
2: 5,
3: 20,
4: 33,
5: 24,
6: 35,
7: 56,
8: 60,
9: 147,
10: 135,
}
4

1 回答 1

1

That's an JavaScript Object. They can't be sorted.

For example, no matter what order you place your elements in, in the code, Google Chrome will automatically sort them when you log the object.

var obj = {
    "0": 3900,
    "1": 42,
    "10": 135,  // See? not sorted.
    "2": 5,
    "3": 20,
    "4": 33,
    "5": 24,
    "6": 35,
    "7": 56,
    "8": 60,
    "9": 147
}
for(key in obj){
    console.log(key, obj[key]);
}

Output:

0 3900
1 42
2 5
3 20
4 33
5 24
6 35
7 56
8 60
9 147
10 135  // Suddenly, without our intervention, the object got sorted by the browser.

So, what I am trying to say is: It's browser-dependent. You can't sort objects. It depends on the browser implementation how the object will be iterated over.

Now, in this specific case, I think it's a better idea to just use an array, since the keys are sequential numbers, any way:

var arr = [3900, 42, 5, 20, 33, 24, 35, 56, 60, 147, 135];

You can access this the same way as you would access your object (arr[5] == 24), and as an added bonus, it has a .length!

于 2013-01-08T09:01:26.450 回答