Javascript对象自动排序

时间:2012-06-12 07:43:16

标签: javascript sorting object

// mechanics
MECHANICS_ISOLATION : 1,
MECHANICS_NA : 2,
MECHANICS_COMPOUND : 3,

// mechanics
Exercise.mechanics = {};
Exercise.mechanics[Exercise.MECHANICS_COMPOUND] = 'Compound';
Exercise.mechanics[Exercise.MECHANICS_ISOLATION] = 'Isolation';
Exercise.mechanics[Exercise.MECHANICS_NA] = 'N/A';

当我遍历Exercise.mechanics时,键出来了。如何让未排序的密钥循环?

谢谢!

2 个答案:

答案 0 :(得分:2)

散列映射中的键不可靠。给你钥匙订单。例如,将密钥放入数组并迭代密钥。

var keys = [MECHANICS_ISOLATION, MECHANICS_NA, MECHANICS_COMPOUND];
for (var i = 0; i < keys.length; i++) {
    console.log(Exercise.mechanics[keys[i]]);
}

答案 1 :(得分:-1)

您期望的订单是什么?我在Fx和IE中没有订购它们

3:Compound
1:Isolation
2:N/A 

使用此代码DEMO

Exercise = {
// mechanics
MECHANICS_ISOLATION : 1,
MECHANICS_NA : 2,
MECHANICS_COMPOUND : 3,
    }

// mechanics
Exercise.mechanics = {};
Exercise.mechanics[Exercise.MECHANICS_COMPOUND] = 'Compound';
Exercise.mechanics[Exercise.MECHANICS_ISOLATION] = 'Isolation';
Exercise.mechanics[Exercise.MECHANICS_NA] = 'N/A';

for (ex in Exercise.mechanics) document.write("<hr>"+ex+":"+Exercise.mechanics[ex])