Adding Key-Value Pairs to JavaScript Objects
In JavaScript, objects are associative collections of key-value pairs. While building an object, you may occasionally need to add new key-value pairs. This process is straightforward and involves the following steps:
Using Dot Notation:
If you know the property name upfront, you can use dot notation to assign a value:
var obj = { key1: value1, key2: value2 }; obj.key3 = "value3";
Using Square Bracket Notation:
Alternatively, you can use square bracket notation when the property name is dynamically determined:
obj["key3"] = "value3";
Properties vs. Array Elements:
Note that the above approaches add properties to an object, which is different from adding elements to an array. Arrays are ordered collections, and elements are accessed using indices. To create an array, you can use either the array literal notation (e.g., []) or the Array constructor (e.g., new Array()).
The above is the detailed content of How Do I Add Key-Value Pairs to JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!