简体   繁体   English

将数据动态添加到 javascript 地图

[英]Dynamically add data to a javascript map

Is there a way I can dynamically add data to a map in javascript.有没有办法可以在javascript中动态地将数据添加到地图中。 A map.put(key,value) ?一个map.put(key,value) I am using the yui libraries for javascript, but didn't see anything there to support this.我正在为 javascript 使用 yui 库,但没有看到任何支持它的内容。

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 facilities for creating object properties that aren't enumerable, and it's pretty easy to do. 2014年2月13日 -现代JavaScript有设施 ,用于创建不枚举对象的属性,这是很容易做到。 However, it's still the case that a "put" property, enumerable or not, would claim the property name "put" and make it unavailable. 但是,仍然存在这样一种情况,即“可放置”属性(可枚举与否)将声明属性名称“put”并使其不可用。 That is, there's still only one namespace per object. 也就是说,每个对象仍然只有一个命名空间。

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 这具有可用于处理查找的方法的优点,例如boolean .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之前使用它来处理查找不存在的键

I like this way to achieve this我喜欢这种方式来实现这一目标

const M = new Map(Object.entries({ 
  language: "JavaScript" 
}));

console.log(M.size); // 1 
console.log(...M); // ["language", "JavaScript"]

// (1) Add and update some map entries 
M.set("year", 1991); 
M.set("language", "Python");

console.log(M.size); // 2 
console.log(...M); // \["language", "Python"\] ["year", 1991]

In Typescript在打字稿中

 let ar = [1, 2, 3, 4, 5, 6]; let map = new Map<number, string>(); ar.forEach(value => { map.set(value, 'value'+ value); }); console.log(map, 'map data');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM