简体   繁体   English

尝试通过不存在的键“立即”向JavaScript关联数组添加新值

[英]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): 处理未定义对象属性的最佳方法是使用Proxy对象( 答案涵盖了类似的用例):

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. 代理是(不错的)ES6功能。 Firefox supports them since version 18, while in Chrome (and in Node.js) you have to enable the harmony flag. Firefox自版本18开始支持它们,而在Chrome(和Node.js)中,您必须启用和声标志。

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 您可以使用如下所示的自定义getter方法“ getProp”创建对象,并且可以根据需要访问不存在的键,但是请确保不存在的键需要的默认值是什么

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'} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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