javascript关联数组 [英] javascript Associate array

查看:141
本文介绍了javascript关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,我可以执行类似 myMap = {key:[value1,value2]} 的操作,然后访问 value2 使用 myMap [key] [1]

In python I could do something like myMap = {key: [value1, value2]} and then access the value2 using myMap[key][1]

我可以在javascript中执行类似的操作吗?

Can I do something like this in javascript?

推荐答案

嗯,你可以这样做:

var myMap = { key: [ value1, value2 ] };
var array = myMap.key; // or myMap["key"]

JavaScript没有关联数组类型,将map行为与数组行为结合起来的行为,例如跟踪属性的数量。因此,常见的事情是使用普通对象。在现代JavaScript(2017)中,有一个显式的 Map 工具,它允许键属于任何类型,而不仅仅是使用简单对象时的字符串。

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 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:

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"

这篇关于javascript关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆