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

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

    arr.key3 = value3;
    

    because your arr is not really an array... It's a prototype object. The real array would be:

    var arr = [{key1: value1}, {key2: value2}];
    

    but it's still not right. It should actually be:

    var arr = [{key: key1, value: value1}, {key: key2, value: value2}];
    

提交回复
热议问题