地图默认值

New*_*bie 2 javascript arrays dictionary default-value

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

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

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

Jam*_*mes 8

截至2022年,Map.prototype.emplace已达到第2阶段

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


小智 6

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

如果您只想打印一个列表,则只要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'));
Run Code Online (Sandbox Code Playgroud)

但是,如果这不能满足您的需求,并且您确实想要一个具有默认值的地图,则可以为其编写自己的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'));
Run Code Online (Sandbox Code Playgroud)

  • `get` 的另一种实现是使用 `if (!this.get(key) this.set(key, this.default());`。这将允许像 `m.get(' 这样方便的单行代码key').push(newValue)`,代价是让`get`方法改变对象,这有点尴尬 (3认同)