Automatically create object if undefined

后端 未结 12 1042
Happy的楠姐
Happy的楠姐 2020-12-07 13:07

Is there an easy way to automatically add properties to objects if they don\'t allready exist?

Consider the following example:

var test = {}
test.hel         


        
12条回答
  •  温柔的废话
    2020-12-07 13:35

    I've come up with something, really custom as well, but it works as far as I have tested.

    function dotted_put_var(str,val) {
        var oper=str.split('.');
        var p=window;
        for (var i=0;i

    Then, a complex variable can be set like this, ensuring that every links will be created if not already:

    dotter_put_var('test.hello.world', 'testvalue'); // test.hello.world="testvalue";
    

    See this working FIDDLE.

提交回复
热议问题