获取或设置一个Javascript ES6地图中的元素? [英] Get or set element in a Javascript ES6 Map?

查看:207
本文介绍了获取或设置一个Javascript ES6地图中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Javascript中查找或添加元素? Map

我想一步完成以下操作(避免在密钥的正确位置查找两次) :

  //如果键存在,则获取该值,否则设为默认值
let aValue = aMap.get (aKey)
if(aValue == null){
aMap.set(aKey,aDefaultValue)
}

相反,我只想搜索一次该键。



在c ++中,可以使用 std :: map :: insert() std: :map :: lower_bound()



在javascript中,代码可能如下所示:

<$ p (aValue == null)
let aValue = aMap.getValue(iterator)
let arator = aMap.getPosition(aKey)
let aValue =
{
aMap.setWithHint(aKey,aValue,iterator)
}





  let aValue = aMap.getOrSet(aKey,aDefaultValue)

我想这是不可能的,但我想确保我是正确的。我也有兴趣知道为什么它是不可能的,而这是一个重要的功能。
解决方案

无论如何,至少在发动机得到更多的优化之前,如果避免的话,这并不重要。

但是 Map.has 是一个更好的解决方案,应该比 Map获得()。例如:

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



除非你是google-scale,否则性能应该与这个级别无关。但是,如果这是一个严重的瓶颈,那么在可预见的未来,Array还是会比Map / Set更快。

Is it possible to find or add an element in one step in a 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()

In javascript the code could look like this:

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(). For example:

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

Performance should be irrelevant on this level unless you're google-scale. But if it's a serious bottleneck, an Array should still be faster than Map/Set for the forseeable future.

这篇关于获取或设置一个Javascript ES6地图中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆