Defaultdict equivalent in javascript

前端 未结 5 1213
小蘑菇
小蘑菇 2020-12-29 22:32

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

5条回答
  •  被撕碎了的回忆
    2020-12-29 23:37

    I don't think there is the equivalent but you can always write your own. The equivalent of a dictionary in javascript would be an object so you can write it like so

    function defaultDict() {
        this.get = function (key) {
            if (this.hasOwnProperty(key)) {
                return key;
            } else {
                return 0;
            }
        }
    }
    

    Then call it like so

    var myDict = new defaultDict();
    myDict[1] = 2;
    myDict.get(1);
    

提交回复
热议问题