使用JSON数据,javascript会改变对象的顺序:
{
"01": { "disabled": 0, "factor": 10, "id": "01", "tickets": 0 },
"02": { "disabled": 0, "factor": 10, "id": "02", "tickets": 0 },
"03": { "disabled": 0, "factor": 10, "id": "03", "tickets": 0 },
"04": { "disabled": 0, "factor": 10, "id": "04", "tickets": 0 },
"05": { "disabled": 0, "factor": 10, "id": "05", "tickets": 0 },
"06": { "disabled": 0, "factor": 10, "id": "06", "tickets": 0 },
"07": { "disabled": 0, "factor": 10, "id": "07", "tickets": 0 },
"08": { "disabled": 0, "factor": 10, "id": "08", "tickets": 0 },
"09": { "disabled": 0, "factor": 10, "id": "09", "tickets": 0 },
"10": { "disabled": 0, "factor": 10, "id": "10", "tickets": 0 },
"11": { "disabled": 1, "factor": 40, "id": "11", "tickets": 0 }
}
对此:
{
"10": { "disabled": 0, "factor": 10, "id": "10", "tickets": 0 },
"11": { "disabled": 1, "factor": 40, "id": "11", "tickets": 0 },
"01": { "disabled": 0, "factor": 10, "id": "01", "tickets": 0 },
"02": { "disabled": 0, "factor": 10, "id": "02", "tickets": 0 },
"03": { "disabled": 0, "factor": 10, "id": "03", "tickets": 0 },
"04": { "disabled": 0, "factor": 10, "id": "04", "tickets": 0 },
"05": { "disabled": 0, "factor": 10, "id": "05", "tickets": 0 },
"06": { "disabled": 0, "factor": 10, "id": "06", "tickets": 0 },
"07": { "disabled": 0, "factor": 10, "id": "07", "tickets": 0 },
"08": { "disabled": 0, "factor": 10, "id": "08", "tickets": 0 },
"09": { "disabled": 0, "factor": 10, "id": "09", "tickets": 0 }
}
注意" 10"和" 11"即使在最初的JSON中,开头的行也在最后。
我解决了这个问题:
var data = JSON.parse(json_data);
var keys = Object.keys(data).sort();
for ( var k in keys )
{
var key = keys[k];
var row = data[key];
console.log(row);
};
如何防止javascript更改行的顺序?
那个错误(因为它)让我发疯了。 : - /
感谢您的帮助。
答案 0 :(得分:1)
您应该检查bpierre对"Does JavaScript Guarantee Object Property Order?"的答案。
总结一下,ECMAScript中对象的定义是
这是一个无序的属性集合[...]
在他的回答中,他建议在更新版本的JavaScript中使用Map
。
所以答案是否定的,你不能阻止JavaScript改变JSON的顺序,因为首先没有确定的顺序。