gpt4 book ai didi

javascript - 可以强制 chrome 按存储顺序迭代 "string numeric"键

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:19:31 26 4
gpt4 key购买 nike

我似乎只在 chrome(不是 IE、FF)中遇到了一个有趣的问题。给定以下对象:

var myObj = {
"59" : "Hello",
"52" : "and",
"50" : "how",
"31" : "are",
"65" : "you"
};

通过 for 循环遍历此对象会按以下顺序吐出内容:

for(var j in myObj) {  document.write(myObj[j] +', '); }

are, how, and, hello, you

所有其他主要浏览器都以“正确”的顺序给出它。 Chrome 将键视为整数而不是字符串。问题是我有一个无法更改的 json 数据源,我需要按照项目在对象中的顺序访问这些项目。

有人可以建议在 Google Chrome 中执行此操作的方法吗?

最佳答案

当通过 for...in 遍历对象时,不保证属性的顺序。你无能为力:

A for...in loop iterates over the properties of an object in an arbitrary order (see the delete operator for more on why one cannot depend on the seeming orderliness of iteration, at least in a cross-browser setting).

删除页面:

Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its old position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.

So if you want to simulate an ordered associative array in a cross-browser environment, you are forced to either use two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.

关于javascript - 可以强制 chrome 按存储顺序迭代 "string numeric"键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4686891/

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