在Javascript的Map中是否可能在一个步骤中查找或添加元素?
我想要在一个步骤中完成以下操作(避免两次查找正确的键位置):
// get the value if the key exists, set a default value otherwise
let aValue = aMap.get(aKey)
if(aValue == null) {
aMap.set(aKey, aDefaultValue)
}
我希望只搜索一次密钥。
在c++中,可以使用std::map::insert()或std::map::lower_bound()
在javascript中,代码可以如下所示:
let iterator = aMap.getPosition(aKey)
let aValue = aMap.getValue(iterator)
if(aValue == null)
{
aMap.setWithHint(aKey, aValue, iterator)
}
或者
let aValue = aMap.getOrSet(aKey, aDefaultValue)
我认为这是不可能的,但我想确定我是正确的。同时,我也想知道为什么它是一个重要的功能却不可能实现。
aKey
需要被查找两次? - nils