Automatically create object if undefined

后端 未结 12 1041
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:56

    var test = {}
    test.hello.world = "Hello doesn't exist!"
    

    This will throw an error obviously as you didn't defined the test.hello

    Firstly you need to need define the hello key then inside you can assign any key. But if you want to create key if not exists then you can do following thing

    test.hello = test.hello || {};
    

    The above statement will create the test.hello object if not defined and if it is defined then it will assign the same value as it is previously

    Now you can assign any new key inside the test.hello

    test.hello.world = "Everything works perfect";
    
    test.hello.world2 = 'With another key too, it works perfect';
    

提交回复
热议问题