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