在Javascript中创建关联数组 [英] Create Associative array in Javascript

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

问题描述

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

I have object which contains array and I want it contains the associative array so keys are strings. How to do it? This does not work:

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

我想避免

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

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

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

我知道的另一种方式是: array ['key2'] ='新值'; 但这不是对象的一部分,因此我需要将命令拆分为多行-这不是我想要的.

Another way I know is this: array['key2']='new value'; but that is not part of the object so I would need to split 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开始,它还具​​有地图与对象相似,因为您可以给它们命名的值,但也保留按此顺序排列的数组.没有用于创建地图的文字语法.

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天全站免登陆