JavaScript中的有序哈希 [英] Ordered hash in JavaScript
本文介绍了JavaScript中的有序哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
JavaScript对象没有为属性存储订单(根据规范)。当在循环中使用 for ...时,Firefox似乎保留了属性定义的顺序。这种行为是我可以依赖的吗?如果没有,那里有一段实现有序哈希类型的JavaScript代码?
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
loop. Is this behaviour something that I can rely on? If not is there a piece of JavaScript code somewhere that implements an ordered hash type?
推荐答案
这个问题出现在顶级搜索中结果。在没有找到有序哈希之后,我只是写了这个小小的coffescript。希望这有助于人们登陆此页面:
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
这篇关于JavaScript中的有序哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文