Ordered hash in JavaScript

前端 未结 9 1010
心在旅途
心在旅途 2020-12-05 17:34

JavaScript objects have no order stored for properties (according to the spec). Firefox seems to preserve the order of definition of properties when using a for...in<

9条回答
  •  情话喂你
    2020-12-05 17:45

    One trick I do is to store the data in a regular unordered hash, and then store the preferred order in an array. In JS, you can even make the order array part of the hash itself.

    var myHash = {
      a: "2",
      b: "3",
      c: "1"
    };
    
    myHash.order = [ myHash.c, myHash.a, myHash.b ];
    
    alert("I can access values by key. Here's B: " + myHash.b);
    var message =  "I can access also loop over the values in order: ";
    
    for (var i=0;i

    It's not exactly elegant, but it gets the job done.

提交回复
热议问题