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

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

    You can create a class with the answer of @Ionuț G. Stan

    function obj(){
        obj=new Object();
        this.add=function(key,value){
            obj[""+key+""]=value;
        }
        this.obj=obj
    }
    

    Creating a new object with the last class:

    my_obj=new obj();
    my_obj.add('key1', 'value1');
    my_obj.add('key2', 'value2');
    my_obj.add('key3','value3');
    

    Printing the object

    console.log(my_obj.obj) // Return {key1: "value1", key2: "value2", key3: "value3"} 
    

    Printing a Key

    console.log(my_obj.obj["key3"]) //Return value3
    

    I'm newbie in javascript, comments are welcome. Works for me.

提交回复
热议问题