gpt4 book ai didi

javascript - for-in 循环在后续执行中是否以相同的顺序迭代?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:30:14 24 4
gpt4 key购买 nike

众所周知,ECMA 标准不保证特定的迭代顺序,但我对实际的迭代顺序不感兴趣。我需要知道的是:如果在同一 session 中执行多次,for-in 循环至少保证相同的迭代顺序,前提是在后续的 for-in 执行之间显然没有添加或删除迭代对象的属性?我猜想没有理由不应该发生这种情况,但我想找到一些引用。

最佳答案

顺序是任意的,你只能猜测它总是以相同的顺序迭代。只是不要期望它总是一样。

以下报价适用于 for-in用在数组上,同样适用于在对象属性上使用它。

Because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order.

delete operator添加一些额外的信息:

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.

关于javascript - for-in 循环在后续执行中是否以相同的顺序迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31949284/

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