How can I add a key/value pair to a JavaScript object?

前端 未结 24 3347
情歌与酒
情歌与酒 2020-11-21 07:01

Here is my object literal:

var obj = {key1: value1, key2: value2};

How can I add field key3 with value3 to the ob

24条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 07:39

    According to Property Accessors defined in ECMA-262(http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf, P67), there are two ways you can do to add properties to a exists object. All these two way, the Javascript engine will treat them the same.

    The first way is to use dot notation:

    obj.key3 = value3;
    

    But this way, you should use a IdentifierName after dot notation.

    The second way is to use bracket notation:

    obj["key3"] = value3;
    

    and another form:

    var key3 = "key3";
    obj[key3] = value3;
    

    This way, you could use a Expression (include IdentifierName) in the bracket notation.

提交回复
热议问题