gpt4 book ai didi

javascript - 映射默认值

转载 作者:行者123 更新时间:2023-12-01 09:44:54 26 4
gpt4 key购买 nike

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

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

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

最佳答案

首先回答关于标准的问题Map : Javascript Map正如 ECMAScript 2015 中提议的那样,不包括默认值的 setter 。但是,这并不妨碍您自己实现该功能。
如果您只想打印一个列表,只要 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 ,您可以为它编写自己的 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']

关于javascript - 映射默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51319147/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com