Elements order in a “for (… in …)” loop

后端 未结 9 700
终归单人心
终归单人心 2020-11-21 07:27

Does the \"for…in\" loop in Javascript loop through the hashtables/elements in the order they are declared? Is there a browser which doesn\'t do it in order?
The object

9条回答
  •  太阳男子
    2020-11-21 08:17

    From the ECMAScript Language Specification, section 12.6.4 (on the for .. in loop):

    The mechanics of enumerating the properties is implementation dependent. The order of enumeration is defined by the object.

    And section 4.3.3 (definition of "Object"):

    It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

    I guess that means you cant rely on the properties being enumerated in a consistent order across JavaScript implementations. (It would be bad style anyway to rely on implementation-specific details of a language.)

    If you want your order defined, you will need to implement something that defines it, like an array of keys that you sort before accessing the object with it.

提交回复
热议问题