简体   繁体   English

按添加元素的顺序遍历字典

[英]Iterating over a dictionary in order of addition of elements

I am having a dictionary which maps question-id to the question . 我有一本字典,将问题ID映射到问题 While printing contents of dictionary, I want to access the elements in the order in which they were added. 在打印字典内容时,我想按添加顺序访问元素。 The question id is a random 10-digit string. 问题ID是10位随机字符串。 This printing will be done numerous times. 该打印将进行多次。 A dictionary elements can also be deleted in which case it will simply disappear while leaving the other elements in the exact same order. 字典元素也可以删除,在这种情况下,字典元素将消失而其他元素以完全相同的顺序保留。

It is probably not possible without creating a dictionary class of my own. 如果不创建自己的字典类,可能是不可能的。 Or is it? 还是?

var question_dic = {};
question_dic["2186242050"] = "Answer to life, universe and everything?";   //adding a key-value pair
delete question_dic[delete_key];   //remove delete_key key

It is probably not possible without creating a dictionary class of my own. 如果不创建自己的字典类,可能是不可能的。

Yes, that's true. 是的,这是真的。 You cannot (and should not) use objects like that. 您不能(也不应)使用类似的对象。

However, this is exactly the use case that Map s are introduced for in ES6. 但是,这恰恰是在ES6中引入Map用例。 And even if you are not running your scripts in an ES6 environment, you don't need to create such a dictionary class of your own , as there exists a variety of polyfills. 而且,即使您不在ES6环境中运行脚本,也无需创建自己的字典类,因为存在多种polyfill。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM