繁体   English   中英

如何从Map返回默认值?

[英]How to return a default value from a Map?

使用ES6代理对象时,可以在普通对象中不存在属性时返回默认值。

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy

如何用地图做到这一点? 我尝试了以下代码,但始终返回默认值:

var map = new Map ([
    [1,  'foo'],  // default
    [2,  'bar'],
    [3,  'baz'],
]);

var mapProxy = new Proxy(map, {
    get: function(target, id) {
        return target.has(id) ? target.get(id) : target.get(1);
    },
});

console.log( mapProxy[3] );  // foo

那是因为您的地图键是数字,但代理属性名称始终是一个字符串。 您需要先将id转换为数字。

工作示例(需要现代JS引擎):

 var map = new Map ([ [1, 'foo'], // default [2, 'bar'], [3, 'baz'], ]); var mapProxy = new Proxy(map, { get: function(target, id) { // Cast id to number: id = +id; return target.has(id) ? target.get(id) : target.get(1); }, }); console.log( mapProxy[3] ); // baz console.log( mapProxy[10] ); // foo 

在Scala中,地图是具有getOrElse方法的monad。 如果monad(容器)不包含任何值,则其get方法会因异常而失败,但getOrElse允许用户编写可靠的代码

Map.prototype.getOrElse = function(key, value) {
  return this.has(key) ? this.get(key) : value
}

var map = new Map ([[1,  'foo'],  [2,  'bar'], [3,  'baz']]); 
[map.get(1), map.getOrElse(10, 11)]; // gives 11

另一种选择是使用withDefaultValue方法扩展您的地图

//a copy of map will have a default value in its get method
Map.prototype.withDefaultValue = function(defaultValue) {
  const result = new Map([...this.entries()]); 
  const getWas = result.get; result.get = (key) => 
    result.has(key) ? getWas.call(this, key) : defaultValue; 
  return result
}
map.withDefaultValue(12).get(10) // gives 12

这是在Scala中完成的方式。 或者,至少,看起来那样。

暂无
暂无

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

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