映射默认值

问题描述 投票:2回答:1

我正在寻找像Map这样的默认值。

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

现在结果是Undefined但我想得到空数组[]。

javascript arrays dictionary default-value
1个回答
3
投票

首先回答有关标准Map的问题:ECMAScript 2015中提出的Javascript Map不包含默认值的setter。但是,这并不会限制您自己实现该功能。

如果你只想打印一个列表,每当m [what]未定义时,你可以只是: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) {
    return super.get(key) || this.default;
  }
  
  constructor(defaultValue) {
    super();
    this.default = defaultValue;
  }
}

// And use it like:
const m = new MapWithDefault([]);
console.log(m.get('whatever'));
© www.soinside.com 2019 - 2024. All rights reserved.