简体   繁体   English

Javascript-将Map对象的所有键设置为一个值

[英]Javascript - set all keys of a Map object to a value

I have this code here: 我在这里有此代码:

const myMap = new Map()

myMap.set("banana", true)
myMap.set("apple", true)

Object.keys(myMap).forEach(key => {myMap.set(key, false)})

console.log(myMap.get("banana")) // returns true should return false
console.log(myMap.get("apple")) // returns true should return false

I want to set all the values of this Map to false , but it doesn't work at all. 我想将此Map所有值设置为false ,但是它根本不起作用。

I've tried something like this: 我已经尝试过这样的事情:

Object.keys(myMap).forEach(key => myMap[key] = false)

but this doesn't work either. 但这也不起作用。

Is there a way to fill all keys of a Map to a specific value ? 有没有办法将Map所有键填充为特定

You have to specifically call Map.set in order to set a value in a Map. 您必须专门调用Map.set才能在Map中设置值。 myMap[key] = value will only work for plain objects . myMap[key] = value仅适用于普通对象 You should also use myMap.keys() to get an iterator of the map's keys: 您还应该使用myMap.keys()获取地图按键的迭代器:

 const myMap = new Map(); myMap.set("banana", true); myMap.set("apple", true); [...myMap.keys()].forEach((key) => { myMap.set(key, false); }); console.log(myMap.get("banana")); console.log(myMap.get("apple")); 

A Map has a .forEach() method for traverse it, that you can use in this particular case: Map具有用于遍历它的.forEach()方法,您可以在这种特殊情况下使用:

 const myMap = new Map(); myMap.set("banana", true); myMap.set("apple", true); myMap.forEach((value, key, map) => map.set(key, false)); console.log( "Banana:", myMap.get("banana"), "Apple:", myMap.get("apple") ); 
 .as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;} 

The documentation of the callback invoked on each element, from MDN , says: MDN调用每个元素的回调的文档说:

The forEach method executes the provided callback once for each key of the map which actually exist. forEach方法对地图中实际存在的每个键执行一次提供的callback It is not invoked for keys which have been deleted. 对于已删除的密钥,不会调用它。 However, it is executed for values which are present but have the value undefined. 但是,它针对存在但未定义的值执行。 The callback is invoked with three arguments: 使用三个参数调用callback

  • the element value 元素value
  • the element key 元素key
  • the Map object being traversed 遍历的Map对象

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

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