【问题标题】:Map default value映射默认值
【发布时间】:2018-12-21 11:34:18
【问题描述】:

我正在寻找类似地图默认值的东西。

m = new Map();
//m.setDefVal([]); -- how to write this line???
console.log(m[whatever]);

现在结果是未定义,但我想得到空数组 []。

【问题讨论】:

  • 一个空数组是空的,因此在索引[0]处没有元素
  • m[whatever] || []

标签: javascript arrays dictionary default-value


【解决方案1】:

截至 2022 年,Map.prototype.emplace 已达到stage 2

正如提案页面上所说,core-js 库中提供了一个 polyfill。

【讨论】:

    【解决方案2】:

    首先回答关于标准Map 的问题:ECMAScript 2015 中提出的 Javascript Map 不包括默认值的设置器。但是,这并不妨碍您自己实现该功能。

    如果您只想打印一个列表,只要 m[whatever] 未定义,您可以: console.log(m.get('whatever') || []); 正如 Li357 在他的评论中指出的那样。

    如果你想重用这个功能,你也可以把它封装成这样的函数:

    function getMapValue(map, key) {
        return map.get(key) || [];
    }
    
    // And use it like:
    const m = new Map();
    console.log(getMapValue(m, 'whatever'));

    但是,如果这不能满足您的需求,并且您确实想要一个具有默认值的地图,您可以为它编写自己的 Map 类,如下所示:

    class MapWithDefault extends Map {
      get(key) {
        if (!this.has(key)) {
          this.set(key, this.default());
        }
        return super.get(key);
      }
      
      constructor(defaultFunction, entries) {
        super(entries);
        this.default = defaultFunction;
      }
    }
    
    // And use it like:
    const m = new MapWithDefault(() => []);
    m.get('whatever').push('you');
    m.get('whatever').push('want');
    console.log(m.get('whatever')); // ['you', 'want']

    【讨论】:

    • 我相信你应该支持Map构造函数已经需要的东西,不是吗?
    • 在类实现中,您传递一个新对象并将其用作引用,因此每次使用 m.get 时,我们都会返回相同的对象。我认为您应该使用 defaultValue 作为返回数组新实例的函数。
    • get 的替代实现是使用if (!this.get(key) this.set(key, this.default());。这将允许像m.get('key').push(newValue) 这样方便的单行函数,但代价是使get 方法改变对象,这有点尴尬
    • @YiJiang 的做法与 Python 的 defaultdict 一致,并不令人惊讶。我已经相应地编辑了答案。
    猜你喜欢
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    相关资源
    最近更新 更多