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

前端 未结 24 3313
情歌与酒
情歌与酒 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:35

    Two most used ways already mentioned in most answers

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

    One more way to define a property is using Object.defineProperty()

    Object.defineProperty(obj, 'key3', {
      value: "value3",       // undefined by default
      enumerable: true,      // false by default
      configurable: true,    // false by default
      writable: true         // false by default
    });
    

    This method is useful when you want to have more control while defining property. Property defined can be set as enumerable, configurable and writable by user.

提交回复
热议问题