Javascript array with default values (equivalent of Python's defaultdict)? [duplicate]

Possible Duplicate:
Set undefined javascript property before read

Is there an equivalent of Python's defaultdict in Javascript? This would be a Javascript array where the value returned for a missing key is definable. Something like:

var a = defaultArray("0");
// would print 0

If not, how would you implement it?



No, this is not possible in JavaScript. Btw, you certainly meant Objects (property-value-maps) instead of arrays. Two solutions:

  • Implement your object as a Proxy, which is designed to do exactly what you want. Yet, it is only a draft and currently only supported in Firefox' Javascript 1.8.5.

  • Use a getter function with a string parameter instead of object properties. That function can look up the input key in an internal "dictionary" object, and handle misses programmatically - e.g. creating values dynamically or returning default values.

    Of course you could build a factory for such getter functions.

function defaultDict(map, default) {
    return function(key) {
        if (key in map)
            return map[key];
        if (typeof default == "function")
            return default(key);
        return default;

var a = defaultDict({cat: 1}, 0);
console.log(a('cat')); // 1
console.log(a('dog')); // 0


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.