将数据动态添加到 javascript 地图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2966947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:43:47  来源:igfitidea点击:

Dynamically add data to a javascript map

javascriptdata-structuresmapsyui

提问by stevebot

Is there a way I can dynamically add data to a map in javascript. A map.put(key,value)? I am using the yui libraries for javascript, but didn't see anything there to support this.

有没有办法可以在javascript中动态地将数据添加到地图中。一个map.put(key,value)?我正在为 javascript 使用 yui 库,但没有看到任何支持它的东西。

回答by Pointy

Well any Javascript object functions sort-of like a "map"

好吧,任何 Javascript 对象的功能都类似于“地图”

randomObject['hello'] = 'world';

Typically people build simple objects for the purpose:

通常人们会出于以下目的构建简单的对象:

var myMap = {};

// ...

myMap[newKey] = newValue;

edit— well the problem with having an explicit "put" function is that you'd then have to go to pains to avoid having the function itself look like part of the map. It's not really a Javascripty thing to do.

编辑- 拥有显式“放置”函数的问题在于,您必须费心避免让函数本身看起来像地图的一部分。这不是真正的 Javascripty 事情。

13 Feb 2014— modern JavaScript has facilitiesfor creating object properties that aren't enumerable, and it's pretty easy to do. However, it's still the case that a "put" property, enumerable or not, would claim the property name "put" and make it unavailable. That is, there's still only one namespace per object.

2014年2月13日-现代JavaScript有设施,用于创建不枚举对象的属性,这是很容易做到。但是,仍然存在“put”属性,无论是否可枚举,都会声明属性名称为“put”并使其不可用。也就是说,每个对象仍然只有一个命名空间。

回答by NiallJG

Javascript now has a specific built in object called Map, you can call as follows :

Javascript 现在有一个名为 Map 的特定内置对象,您可以按如下方式调用:

   var myMap = new Map()

You can update it with .set :

您可以使用 .set 更新它:

   myMap.set("key0","value")

This has the advantage of methods you can use to handle look ups, like the boolean .has

这具有可用于处理查找的方法的优点,例如布尔值 .has

  myMap.has("key1"); // evaluates to false 

You can use this before calling .get on your Map object to handle looking up non-existent keys

您可以在调用 Map 对象上的 .get 之前使用它来处理查找不存在的键