javascript 关联数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5434187/
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
javascript Associate array
提问by MxLDevs
In python I could do something like myMap = {key: [value1, value2]}
and then access the value2
using myMap[key][1]
在 python 中,我可以做类似的事情myMap = {key: [value1, value2]}
,然后访问value2
usingmyMap[key][1]
Can I do something like this in javascript?
我可以在 javascript 中做这样的事情吗?
回答by Pointy
Well, you can do this:
好吧,你可以这样做:
var myMap = { key: [ value1, value2 ] };
var array = myMap.key; // or myMap["key"]
JavaScript doesn't have an "associative array" type, one that combines "map" behavior with array behavior like keeping track of the number of properties. Thus the common thing to do is use a plain object. In modern JavaScript now (2017), there's an explicit Map
facility that allows keys to be of any type, not just strings as when using simple objects.
JavaScript 没有“关联数组”类型,一种将“映射”行为与数组行为(如跟踪属性数量)结合起来的类型。因此,常见的做法是使用普通对象。在现代 JavaScript (2017) 中,有一个明确的Map
工具允许键是任何类型,而不仅仅是使用简单对象时的字符串。
JavaScript is a little bit silly about the object literal notation, in that it won't let you use reserved words for keys unless you quote them:
JavaScript 的对象字面量表示法有点愚蠢,因为它不允许您使用保留字作为键,除非您引用它们:
var myMap = { 'function': 'hello world' };
The quote syntax allows any string to be used as a property name. To access such properties, you'd use the [ ]
operator
引号语法允许将任何字符串用作属性名称。要访问此类属性,您可以使用[ ]
运算符
console.log(myMap["function"]); // "hello world"
回答by Swaff
回答by Greg
Yes, and the syntax is almost the same too.
是的,语法也几乎相同。
var myMap = {key: ["value1", "value2"]};
alert(myMap["key"][1]); // pops up an alert with the word "value2"
You can also use the following notation:
您还可以使用以下符号:
myMap.key[1]
回答by Jimmy Chandra
Short answer... yes...
简短的回答......是的......
var m = { Foo : ["Bar", "Baz"] };
alert(m.Foo[0]);
alert(m["Foo"][1]);
回答by Santo Boldi?ar
You can using Map:
您可以使用地图:
var myMap = new Map();
myMap.set('key','Value');
var res = myMap.get('key');
console.log(var); // Result is: 'Value'