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

后端 未结 19 1506
攒了一身酷
攒了一身酷 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:19

    Yes it is possible. Assuming:

    var data = {
        'PropertyA': 1,
        'PropertyB': 2,
        'PropertyC': 3
    };
    var propertyName = "someProperty";
    var propertyValue = "someValue";
    

    Either:

    data[propertyName] = propertyValue;
    

    or

    eval("data." + propertyName + " = '" + propertyValue + "'");
    

    The first method is preferred. eval() has the obvious security concerns if you're using values supplied by the user so don't use it if you can avoid it but it's worth knowing it exists and what it can do.

    You can reference this with:

    alert(data.someProperty);
    

    or

    data(data["someProperty"]);
    

    or

    alert(data[propertyName]);
    

提交回复
热议问题