我有一组键/值,例如orange = 123,banana = 4,apple = 567.如何将这些键/值存储在javascript对象中,以便我可以:
通过查找检索值,例如set ["orange"]应返回123 and,
按照添加键/值对的顺序迭代集合.
似乎对于1.对象文字是合适的但迭代顺序不是保证的,而对于2.一组键/值对(对象文字)将提供迭代顺序而不是基于的查找值的能力关键.
@*感谢所有答案 - 这个问题不是常见问题吗?像jQuery这样的库不包含对这种类型的支持吗?
如何烹饪自己的列表构造函数?
function List(obj) { if (this instanceof List) { var t = this, keys = []; /* inititalize: add the properties of [obj] to the list, and store the keys of [obj] in the private keys array */ for (var l in obj) { keys.push(l); t[l] = obj[l]; } /* public: add a property to the list */ t.add = function(key, value) { t[key] = value; keys.push(key); return t; /* allows method chaining */ }; /* public: return raw or sorted list as string, separated by [separator] Without [sort] the order of properties is the order in which the properties are added to the list */ t.iterate = function(sort,separator){ separator = separator || '\n'; var ret = [], lkeys = sort ? keys.slice().sort() : keys; for (var i=0;i'List(key,value)' */ }
现在你可以让它原始(你添加道具的顺序被维护)或排序:
var myList = List( { orange:123, banana:4, apple:567 } ); myList.add('peach',786); alert(myList.iterate()); /*=>output: orange: 123 banana: 4 apple: 567 peach: 786 */ or: alert(myList.iterate(1)); /*=>output: apple: 567 banana: 4 orange: 123 peach: 786 */