Ordered hash in JavaScript

前端 未结 9 999
心在旅途
心在旅途 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:55

    This question come up as the top search result. After not finding a ordered hash, i just wrote this small coffescript. Hopefully this will help folks landing on this page:

    ## OrderedHash
    # f = new OrderedHash
    # f.push('a', 1)
    # f.keys()
    # 
    class OrderedHash
     constructor: ->
       @m_keys = []
       @m_vals = {}
    
      push: (k,v) ->
        if not @m_vals[k]
          @m_keys.push k
        @m_vals[k] = v
    
      length: () -> return @m_keys.length
    
      keys: () -> return @m_keys
    
      val: (k) -> return @m_vals[k]
      vals: () -> return @m_vals
    

提交回复
热议问题