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

后端 未结 9 690
终归单人心
终归单人心 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:25

    Quoting John Resig:

    Currently all major browsers loop over the properties of an object in the order in which they were defined. Chrome does this as well, except for a couple cases. [...] This behavior is explicitly left undefined by the ECMAScript specification. In ECMA-262, section 12.6.4:

    The mechanics of enumerating the properties ... is implementation dependent.

    However, specification is quite different from implementation. All modern implementations of ECMAScript iterate through object properties in the order in which they were defined. Because of this the Chrome team has deemed this to be a bug and will be fixing it.

    All browsers respect definition order with the exception of Chrome and Opera which do for every non-numerical property name. In these two browsers the properties are pulled in-order ahead of the first non-numerical property (this is has to do with how they implement arrays). The order is the same for Object.keys as well.

    This example should make it clear what happens:

    var obj = {
      "first":"first",
      "2":"2",
      "34":"34",
      "1":"1",
      "second":"second"
    };
    for (var i in obj) { console.log(i); };
    // Order listed:
    // "1"
    // "2"
    // "34"
    // "first"
    // "second"
    

    The technicalities of this are less important than the fact that this may change at any time. Do not rely on things staying this way.

    In short: Use an array if order is important to you.

提交回复
热议问题