javascript - pythonic javascript中的嵌套默认字典
问题描述
我想在javascript中实现一个嵌套的默认字典,所以我可以去
nest['first']['second']['third'] = 'yay'
无需检查或初始化nest['first']
&nest['first']['second']
在python中,这很容易
nested = defaultDict(lambda: deafultDict(dict()))
我尝试使用 Proxy 在 javascript 中实现相同的功能。结果并不像预期的那样,我无法弄清楚我错过了什么。从最后一条日志来看,看起来相同的默认字典正在作为参考传递。如何避免这种情况并使其按预期工作?
function defaultDict (defaultValue) {
const handler = {
get: (obj, prop) => {
return prop in obj ? obj[prop] : defaultValue
}
}
return new Proxy({}, handler)
}
var nested = defaultDict(defaultDict({}))
nested['first']['second']['third'] = 'yay'
console.log(nested['first']['second']['third']) // yay OK
console.log(nested['first']['second']) // {third: 'yay'} OK
console.log(nested['first']) // result: {} expected {second: {third: 'yay'}}
console.log(nested['none']['gggggggggggg']) // result: {third: 'yay'} expected: {}
谢谢!
解决方案
要实现任意深度的自动激活对象,您需要类似的东西
function defaultDict(defaultValueFn) {
const handler = {
get: (obj, prop) => {
if(!(prop in obj)) obj[prop] = defaultValueFn();
return obj[prop];
},
};
return new Proxy({}, handler);
}
var nestedDefaultDict = () => defaultDict(nestedDefaultDict);
var nested = nestedDefaultDict();
nested.a.b.c = 8;
nested.d.e.f = 8;
console.log(nested); // { a: { b: { c: 8 } }, d: { e: { f: 8 } } }
,就像在 Python 中一样defaultdict
,你传入一个返回嵌套对象的可调用对象,而不是对象本身。
推荐阅读
- ios - 运行时错误:“命令 PhaseScriptExecution 失败,退出代码非零”
- javascript - 如何使用 v-for 将不同的组件拉入 div?
- html - HTML 电子邮件 - Outlook.com 正在将 CSS 样式从一个 DOM 元素转移到另一个
- javascript - Uncaught DOMException: Error :hidden' is not a valid selector
- javascript - Mongoose 模型架构引用不起作用 - 电子商务模型
- android - 如何在 Android 环境中使用 os.startfile()?
- algorithm - 如何找到代码的上限和下限?
- vue.js - 如何使用函数在 data() 上的变量内设置值?
- python - 如何用python求解非线性DE的9方程系统?
- php - 如何使用数组中的下拉列表更新 usermeta 字段?