在 JavaScript 中创建一些关联数组

问题描述:

我有一个包含数组的对象,我希望它包含一个关联数组,因此键是字符串.我该怎么做?

I have an object which contains an array, and I want it to contain an associative array so keys are strings. How can I do it?

这不起作用:

{profiles: { easy:["example" : 1], advanced:["example" : 1] }

我想避免

console.log({profiles: { easy: {"example": 1}, advanced:{"example": 1} })

因为easyadvanced成员不是显示为数组而是显示为对象.

Because that easy and advanced members are not displayed as an array but as an object.

我知道的另一种方式是:

Another way I know is this:

array['key2'] = 'new value';

但这不是对象的一部分,所以我需要将命令拆分为多行 - 这不是我想要的.

but that is not part of the object, so I would need to split the command for multiple lines - which is not what I want.

PHP 有类似 array("mykey" => "myValue") 的东西,但 JavaScript 有类似的东西吗?

PHP has something like array("mykey" => "myValue"), but does JavaScript have something similar?

但我不想使用框架.这只是 JavaScript.

Yet I don't want to use frameworks. This is JavaScript only.

JavaScript 没有关联数组".

JavaScript doesn't have "associative arrays".

它有对象,你可以在命名属性中存储值.

It has objects, which you can store values on in named properties.

它有数组,通过整数属性存储一组有序的值.由于它们是一种对象,您还可以在其上存储命名值(但您不能使用文字语法创建它们,只能在创建数组后添加它们)但这不被认为是好的做法,它们将几乎任何对数组进行特殊情况处理的东西都会被忽略.

It has arrays, which store an ordered set of values via integer properties. Since they are a type of object, you can also store named values on them (but you can't create them using the literal syntax, only add them after the array is created) but this isn't considered good practise and they will be ignored by just about anything that has special case handling for arrays.

从 ES6 开始,它还具​​有地图 类似于对象,您可以为它们指定命名值,但也可以保留按该顺序排列的数组.没有用于创建 Map 的文字语法.

As of ES6 it also has Maps which are similar to objects in that you can give them named values, but also to arrays in that order is preserved. There is no literal syntax for creating a Map.