在javascript中的Defaultdict等价物

use*_*455 12 javascript jquery

在python中,您可以使用defaultdict(int)将int存储为值.如果您尝试对字典中不存在的键执行'get',则默认值为零.

你能在javascript/jquery中做同样的事吗?

And*_*son 17

您可以使用JavaScript构建一个 Proxy

var defaultDict = new Proxy({}, {
  get: (target, name) => name in target ? target[name] : 0
})
Run Code Online (Sandbox Code Playgroud)

这使您可以在访问属性时使用与普通对象相同的语法.

defaultDict.a = 1
console.log(defaultDict.a) // 1
console.log(defaultDict.b) // 0
Run Code Online (Sandbox Code Playgroud)

要稍微清理一下,可以将它包装在构造函数中,或者使用类语法.

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
Run Code Online (Sandbox Code Playgroud)

编辑:上述实现仅适用于基元.它应该通过将构造函数作为默认值来处理对象.这是一个应该与原语和构造函数一起使用的实现.

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) // []
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个答案,但如果 defaultVal 是一个 *array*(或任何被引用修改的东西?)可能会产生意想不到的结果。我使用了这个变体:`dd = new Proxy({}, { get: (target, name) => name in target ? target[name] : (target[name]=[]) })`,或者这个变体: `class DefaultDict2 { constructor(defaultValConstructor) { return new Proxy({}, { get: (target, name) => name in target ? target[name] : new defaultValConstructor() }) } }` (6认同)

Bri*_*aum 11

查看pycollections.js:

var collections = require('pycollections');

var dd = new collections.DefaultDict(function(){return 0});
console.log(dd.get('missing'));  // 0

dd.setOneNewValue(987, function(currentValue) {
  return currentValue + 1;
});

console.log(dd.items()); // [[987, 1], ['missing', 0]]
Run Code Online (Sandbox Code Playgroud)


DGS*_*DGS 4

我认为没有等效的东西,但你总是可以编写自己的。javascript 中的字典相当于一个对象,因此您可以像这样编写它

function defaultDict() {
    this.get = function (key) {
        if (this.hasOwnProperty(key)) {
            return key;
        } else {
            return 0;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样称呼它

var myDict = new defaultDict();
myDict[1] = 2;
myDict.get(1);
Run Code Online (Sandbox Code Playgroud)

  • 如果您想将默认值设置为集合(例如列表映射),则这将不起作用。 (5认同)