在 JavaScript 中创建一些关联数组 [英] Creating some associative array in JavaScript

查看:36
本文介绍了在 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.

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

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