Is it possible to add dynamically named properties to JavaScript object?

后端 未结 19 1467
攒了一身酷
攒了一身酷 2020-11-21 05:39

In JavaScript, I\'ve created an object like so:

var data = {
    \'PropertyA\': 1,
    \'PropertyB\': 2,
    \'PropertyC\': 3
};

Is it poss

19条回答
  •  孤街浪徒
    2020-11-21 06:08

    Here, using your notation:

    var data = {
        'PropertyA': 1,
        'PropertyB': 2,
        'PropertyC': 3
    };
    var propName = 'Property' + someUserInput
    //imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to 
    //my object?
    data[propName] = 'Some New Property value'
    

提交回复
热议问题