Adding New Key-Value Pairs to JavaScript Objects
In JavaScript, objects serve as containers for storing key-value pairs. To enhance these objects, you may need to add new fields.
Method 1: Dot Notation (Key Known)
var obj = { key1: value1, key2: value2 }; obj.key3 = "value3";
Method 2: Square Bracket Notation (Dynamic Key)
var obj = { key1: value1, key2: value2 }; obj["key3"] = "value3";
Distinction
Dot notation is preferable when the key name is known upfront. Square bracket notation provides flexibility when determining the key name dynamically.
Array Construction
Array Literal Notation:
var arr = [];
Array Constructor Notation:
var arr = new Array();
Both methods create an empty array in JavaScript.
The above is the detailed content of How Can I Add New Key-Value Pairs to a JavaScript Object?. For more information, please follow other related articles on the PHP Chinese website!