简体   繁体   English

JavaScript6:将元素(键,值)添加到ES6映射

[英]JavaScript6: adding element (key, value) to a ES6 map

In jsx I have a map like: 在jsx中,我有一张类似的地图:

var myMap=Map([['rowNumber', '30'], ['id', '80'], ['firstName', '180'], ['lastName', '180'], ['mobile', '180'], ['username', '180'], ['password', '180']])

how can I do programatically add new element like: ['ssn', '12'] to this map? 如何以编程方式向此地图添加新元素,例如:['ssn','12']?

You're looking for the set method : 您正在寻找set方法

myMap.set('ssn', '12');

If you have an entry tuple, you can use 如果您有一个入口元组,则可以使用

const newEntry = ['ssn', '12'];
myMap.set(newEntry[0], newEntry[1]);
// or also
myMap.set(...newEntry) // however that might be confusing

Take a look at the Map reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map 看看地图参考: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

You can add items to a map with: myMap.set(keyString, "value associated with 'a string'"); 您可以使用以下myMap.set(keyString, "value associated with 'a string'");向地图添加项目: myMap.set(keyString, "value associated with 'a string'");

You can use set() method with spread syntax to add array of two elements as key and value. 您可以使用set()方法和传播语法来添加两个元素组成的数组,作为键和值。

 var myMap = new Map([['rowNumber', '30'], ['id', '80'], ['firstName', '180'], ['lastName', '180'], ['mobile', '180'], ['username', '180'], ['password', '180']]) myMap.set(...['ssn', '12']) for(var i of myMap) console.log(i) 

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

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