Appending Key/Value Pairs to JavaScript Objects
In JavaScript, objects are mutable entities that allow dynamic addition and modification of properties. To incorporate a new key-value pair, such as "key3" with "value3," into an existing object, you have two options:
Dot Notation:
If the property name is known, dot notation provides a straightforward method:
var obj = {key1: value1, key2: value2}; obj.key3 = "value3";
Square Bracket Notation:
Alternatively, square bracket notation offers flexibility when the property name is dynamically determined:
var obj = {key1: value1, key2: value2}; obj["key3"] = "value3";
Notably, this can be useful in situations where the property name is derived from a variable, for example:
var property = "key3"; obj[property] = "value3";
While both methods accomplish the same task, dot notation is preferred when the property name is static, while square bracket notation is more versatile and allows for dynamic property names.
Additional Notes on Arrays:
It's worth mentioning that JavaScript arrays, which are distinct from objects, can also be created using either the array literal notation ([]) or the Array constructor (new Array()). However, arrays handle indexing differently than objects, as they use numeric indices rather than named properties.
The above is the detailed content of How Can I Add Key-Value Pairs to JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!