Automatically create object if undefined

后端 未结 12 1058
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 14:01

    var test = {};
    test.hello = test.hello || {};
    test.hello.world = "Hello world!";
    

    If test.hello is undefined, it gets set to an empty object.

    If test.hello was previously defined, it stays unchanged.

    var test = {
      hello : {
        foobar : "Hello foobar"
      }
    };
    
    test.hello = test.hello || {};
    test.hello.world = "Hello World";
    
    console.log(test.hello.foobar); // this is still defined;
    console.log(test.hello.world); // as is this.
    

提交回复
热议问题