Iteration order of for..in loops in Javascript

后端 未结 5 1725
孤城傲影
孤城傲影 2021-01-17 08:33

Suppose I have a Javascript object which is initialized

var letters = {q:0, t:0, o:0, b:0, y:0, n:0, u:0, m:0, p:0, 
               w:0, a:0, d:0, k:0, v:0,          


        
相关标签:
5条回答
  • 2021-01-17 08:58

    No, you should not rely on this.

    0 讨论(0)
  • 2021-01-17 09:01

    The order is defined in specifications as "arbitrary", so no; you shouldn't rely on the order being definite.

    0 讨论(0)
  • 2021-01-17 09:03

    The order is not guaranteed. See this SO question for more information: Iterate over a Javascript associative array in sorted order.

    0 讨论(0)
  • 2021-01-17 09:06

    To ensure a particular order for processing an object's properties in a for-in loop, you'll need to define a sort order or list method for the object. If you define all the properties when you create the object, an array of property names will do, but if you can add or remove properties, a method is required.

    If the processing order is essential for some reason, an array may be preferable.

    0 讨论(0)
  • 2021-01-17 09:10

    No, it cannot be relied upon, at least not in Firefox:

    A for...in loop iterates over the properties of an object in an arbitrary order.

    0 讨论(0)
提交回复
热议问题