动态地向 javascript 映射添加数据

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

320972 次浏览

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

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.

13 Feb 2014 — modern JavaScript has facilities for 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.

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

   var myMap = new Map()

You can update it with .set :

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

This has the advantage of methods you can use to handle look ups, like the 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

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');