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

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

    I know that the question is answered perfectly, but I also found another way to add new properties and wanted to share it with you:

    You can use the function Object.defineProperty()

    Found on Mozilla Developer Network

    Example:

    var o = {}; // Creates a new object
    
    // Example of an object property added with defineProperty with a data property descriptor
    Object.defineProperty(o, "a", {value : 37,
                                   writable : true,
                                   enumerable : true,
                                   configurable : true});
    // 'a' property exists in the o object and its value is 37
    
    // Example of an object property added with defineProperty with an accessor property descriptor
    var bValue;
    Object.defineProperty(o, "b", {get : function(){ return bValue; },
                                   set : function(newValue){ bValue = newValue; },
                                   enumerable : true,
                                   configurable : true});
    o.b = 38;
    // 'b' property exists in the o object and its value is 38
    // The value of o.b is now always identical to bValue, unless o.b is redefined
    
    // You cannot try to mix both :
    Object.defineProperty(o, "conflict", { value: 0x9f91102, 
                                           get: function() { return 0xdeadbeef; } });
    // throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors
    

提交回复
热议问题