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");
console.log(a['dog']);
// 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.