JavaScript 关联数组 [英] JavaScript associate array

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

问题描述

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

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 没有关联数组"类型,这种类型将映射"行为与诸如跟踪属性数量之类的数组行为相结合.因此,常见的做法是使用普通对象.在现代 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天全站免登陆