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

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

    Be careful while adding a property to the existing object using .(dot) method.

    (.dot) method of adding a property to the object should only be used if you know the 'key' beforehand otherwise use the [bracket] method.

    Example:

       var data = {
            'Property1': 1
        };
        
        // Two methods of adding a new property [ key (Property4), value (4) ] to the
        // existing object (data)
        data['Property2'] = 2; // bracket method
        data.Property3 = 3;    // dot method
        console.log(data);     // { Property1: 1, Property2: 2, Property3: 3 }
        
        // But if 'key' of a property is unknown and will be found / calculated
        // dynamically then use only [bracket] method not a dot method    
        var key;
        for(var i = 4; i < 6; ++i) {
        	key = 'Property' + i;     // Key - dynamically calculated
        	data[key] = i; // CORRECT !!!!
        }
        console.log(data); 
        // { Property1: 1, Property2: 2, Property3: 3, Property4: 4, Property5: 5 }
        
        for(var i = 6; i < 2000; ++i) {
        	key = 'Property' + i; // Key - dynamically calculated
        	data.key = i;         // WRONG !!!!!
        }
        console.log(data); 
        // { Property1: 1, Property2: 2, Property3: 3, 
        //   Property4: 4, Property5: 5, key: 1999 }

    Note the problem in the end of console log - 'key: 1999' instead of Property6: 6, Property7: 7,.........,Property1999: 1999. So the best way of adding dynamically created property is the [bracket] method.

提交回复
热议问题