在javascript中的Defaultdict等价物 [英] Defaultdict equivalent in javascript
问题描述
在python中,你可以有一个defaultdict(int),它将int存储为值。如果你尝试对字典中没有的键进行获取,则默认值为零。
In python you can have a defaultdict(int) which stores int as values. And if you try to do a 'get' on a key which is not present in the dictionary you get zero as default value.
你能在javascript /中做同样的事吗jquery
Can you do the same in javascript/jquery
推荐答案
你可以使用JavaScript构建一个代理
You can build one using a JavaScript Proxy
var defaultDict = new Proxy({}, {
get: (target, name) => name in target ? target[name] : 0
})
这使您可以使用与普通对象相同的语法访问属性时。
This lets you use the same syntax as normal objects when accessing properties.
defaultDict.a = 1
console.log(defaultDict.a) // 1
console.log(defaultDict.b) // 0
要清理一下,你可以在构造函数中包装它,或者使用类语法。
To clean it up a bit, you can wrap this in a constructor function, or perhaps use the class syntax.
class DefaultDict {
constructor(defaultVal) {
return new Proxy({}, {
get: (target, name) => name in target ? target[name] : defaultVal
})
}
}
const counts = new DefaultDict(0)
console.log(counts.c) // 0
编辑:上述实现仅适用于基元。它应该通过将构造函数作为默认值来处理对象。这是一个应该与原语和构造函数一起使用的实现。
The above implementation only works well with primitives. It should handle objects too by taking a constructor function for the default value. Here is an implementation that should work with primitives and constructor functions alike.
class DefaultDict {
constructor(defaultInit) {
return new Proxy({}, {
get: (target, name) => name in target ?
target[name] :
(target[name] = typeof defaultInit === 'function' ?
new defaultInit().valueOf() :
defaultInit)
})
}
}
const counts = new DefaultDict(Number)
counts.c++
console.log(counts.c) // 1
const lists = new DefaultDict(Array)
lists.men.push('bob')
lists.women.push('alice')
console.log(lists.men) // ['bob']
console.log(lists.women) // ['alice']
console.log(lists.nonbinary) // []
这篇关于在javascript中的Defaultdict等价物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!