简体   繁体   English

在 Javascript ES6 Map 中获取或设置元素?

[英]Get or set element in a Javascript ES6 Map?

Is it possible to find or add an element in one step in a Javascript Map ?是否可以在 Javascript Map 中一步查找或添加元素?

I would like to do the following in one step (to avoid looking twice for the right place of the key):我想一步完成以下操作(以避免寻找两次正确的密钥位置):

// get the value if the key exists, set a default value otherwise
let aValue = aMap.get(aKey)
if(aValue == null) {
    aMap.set(aKey, aDefaultValue)
}

Instead I would like to search for the key only once.相反,我只想搜索密钥一次。

In c++, one can use std::map::insert() or std::map::lower_bound()在 C++ 中,可以使用std::map::insert()std::map::lower_bound()

In javascript the code could look like this:在 javascript 中,代码可能如下所示:

let iterator = aMap.getPosition(aKey)
let aValue = aMap.getValue(iterator)
if(aValue == null)
{
    aMap.setWithHint(aKey, aValue, iterator)
}

or

let aValue = aMap.getOrSet(aKey, aDefaultValue) 

I suppose that it is not possible, but I want to make sure I am correct.我想这是不可能的,但我想确保我是正确的。 Also I am interested in knowing why it is not possible while it is an important feature.我也很想知道为什么它是一个重要的特性却是不可能的。

The lookup has to happen anyway, it doesn't matter much if you avoid it, at least until the engines are optimized much more.无论如何,查找必须发生,如果你避免它并不重要,至少在引擎被进一步优化之前。

But Map.has is a nicer solution and should be a bit faster than Map.get() .但是Map.has是一个更好的解决方案,应该比Map.get()快一点。 For example:例如:

myMap.has(myKey) ? true : myMap.set(myKey, myValue)

Performance should be irrelevant on this level unless you're google-scale.除非您是 google-scale,否则性能在此级别上应该无关紧要。 But if it's a serious bottleneck, an Array should still be faster than Map/Set for the forseeable future.但如果这是一个严重的瓶颈,在可预见的未来,Array 仍然应该比 Map/Set 快。

I personally ended up changing my Map to a simple Object.我个人最终将我的 Map 更改为一个简单的 Object。 That allows to write a reduce (that groups entries into a Map of Sets) like this:这允许像这样编写一个reduce(将条目分组到一个集合映射中):

.reduce((a, [k, v]) => (a[k] = a[k] || new Set()).add(v) ? a : a, {})

With Map it should have become使用 Map 它应该变成

.reduce((a, [k, v]) => (a.has(k) ? a : a.set(k, new Set())).get(k).add(v) ? a : a, new Map())

That feels little too cumbersome for this purpose.对于这个目的,这感觉有点太麻烦了。

I agree that something like this would be ideal if ever supported:我同意,如果支持的话,这样的事情将是理想的:

.reduce((a, [k, v]) => a.getOrSet(k, new Set()).add(v) ? a : a, new Map())

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

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