简体   繁体   中英

Adding new value to javascript associative array “on the fly” when trying to get value by not existing key

Is it possible to create and return new element of associative array "on the fly" when trying to get value by not existing key?

a = {};
a[5]; // return "fezzes"; a = {5: "fezzs"}
a[9]; // return "jtte";  a = {5: "fezzs", 9: "jtte"}

The best way to handle undefined object properties would be to use a Proxy object (and this answer has covers a similar use case):

a = { 1 : "hello" };

console.log(a[1]); //hello
console.log(a[2]); //undefined

var handler = {
    get: function(target, name){
        if (!(name in target)) {
            target[name] = "world";
        }
        return target[name];
    }
};

var p = new Proxy(a, handler);

console.log(a[1]); //hello
console.log(a[2]); //world

Proxies are a (nice) ES6 features. Firefox supports them since version 18, while in Chrome (and in Node.js) you have to enable the harmony flag.

you can create the object with custom getter method "getProp" like below, and you can access non existing keys as your wish, but make sure what is the default value you need on non existing keys

var t = Object.create({},{
                           getProp:{
                                     enumerable: false,
                                     value:function(a){
                                                        if(!this[a])this[a] =  'defaultValue'; 
                                                        return this[a];
                                   }
                          }
        });

out put

t.getProp('nonExistingKey') // return 'defaultValue', t return {'nonExistingKey': 'defaultValue'} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM