gpt4 book ai didi

javascript - 防止 javascript 改变 JSON 的顺序

转载 作者:行者123 更新时间:2023-12-03 04:56:20 26 4
gpt4 key购买 nike

使用 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 }
}

请注意,即使在原始 JSON 中,开头的“10”和“11”行也位于末尾。

我用这个修复它:

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改变行的顺序?

那个错误(因为确实如此)让我很生气。 :-/

感谢您的帮助。

最佳答案

您应该检查bpierre的回答"Does JavaScript Guarantee Object Property Order?" .

总而言之,ECMAScript 中对象的定义是这样的

It is an unordered collection of properties [...]

在他的回答中,他建议在最新版本的 JavaScript 中使用 Map

所以答案是否定的,你无法阻止 JavaScript 改变 JSON 的顺序,因为一开始就没有明确的顺序。

关于javascript - 防止 javascript 改变 JSON 的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42420916/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com