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)
现在结果是未定义,但我想获取空数组[]。
小智 6
首先回答有关标准的问题Map:MapECMAScript 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)
| 归档时间: |
|
| 查看次数: |
4583 次 |
| 最近记录: |