In JavaScript, objects are collections of key/value pairs. To add a new key/value pair to an existing object, there are two common approaches:
1. Dot Notation:
If the key is known beforehand, you can use dot notation to assign a new value to the object:
var obj = { key1: 'value1', key2: 'value2' }; obj.key3 = 'value3';
2. Square Bracket Notation:
For dynamically generated keys or when the key name is not known in advance, square bracket notation can be used:
obj['key3'] = 'value3';
Both methods achieve the same result, creating a new key/value pair within the object. Dot notation is preferred when the key is known, while square bracket notation is used when the key is determined dynamically.
In addition to objects, JavaScript also has arrays, which are ordered collections of values. Arrays can be created using:
Arrays can be accessed and modified using both index and key-based syntax:
// Array Index Syntax arr[0] = 'element1'; arr[1] = 'element2'; // Array Key-Based Syntax arr['0'] = 'element1'; arr['1'] = 'element2';
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!