Javascript 如何在javascript中创建动态地图键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5455886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create dynamic Map key in javascript?
提问by Sthepen
I have tried to create a map like example below...
我试图创建一个像下面的例子的地图......
var myMap= {"one": 1,"two": "two","three": 3.0};
So, I iterate them like:
所以,我像这样迭代它们:
for (var key in myMap) {
window.alert("myMapmap property \"" + key + "\" = " + myMap[key]);
}
If my data is dynamic... and I want to add each of them in to map... how the codes should be like? And I expect the key is not static...I mean the data taken from other source like database, that wasn't define before..
如果我的数据是动态的……并且我想将它们中的每一个都添加到地图中……代码应该是什么样的?而且我希望密钥不是静态的......我的意思是从其他来源(如数据库)获取的数据,这是之前没有定义的......
Thanks before
之前谢谢
回答by Raynos
var dataSource = ...;
while (var o = dataSource.get()) {
myMap[o.key] = o.value;
}
for (var key in myMap) {
alert("key : " + key + " value : " + myMap[key]);
}
You can simply write to an object using array like syntax.
您可以使用类似数组的语法简单地写入对象。
How and where you get your data is upto you.
获取数据的方式和地点由您决定。
回答by David Tang
Dynamic valuesand keyscan be added using this notation:
可以使用以下表示法添加动态值和键:
var myMap = {}; // Create empty map
myMap["some" + "dynamic" + "key"] = "some" + "dynamic" + "variable";