[英]How to easily increment values for a key inside a Map
If I use object literal as a map, I can simply do: obj[key]++
, but for a map created through new Map
, right now I had to do the follows: 如果将对象文字用作地图,则可以简单地执行:
obj[key]++
,但是对于通过new Map
创建的new Map
,现在我必须执行以下操作:
let currentVal = myMap.get(key);
myMap.set(currentVal + 1);
Which is a lot of typing and no where near elegant. 打字很多,没有什么优雅的。 I read up on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map but there doesn't seem to be an example that covers my use case.
我阅读了MDN: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map,但似乎没有一个涵盖我的用例的示例。
A lot of times if you're storing primitives in the map you're kind of doing it wrong anyway. 很多时候,如果您将基元存储在地图中,无论如何都会犯错。 A lot of times you want to associate that value with other properties.
很多时候,您想将该值与其他属性相关联。 In any event, while it's a little more overhead, you can simplify it by storing an Object instead of primitive.
无论如何,虽然这会增加一些开销,但是您可以通过存储一个Object而不是Primitive来简化它。
myMap.set({ value: initialValue });
// later
myMap.get(key).value++;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.