Adding Key/Value Pairs to JavaScript Objects
Adding new properties to a JavaScript object is essential for manipulating and extending its functionality. This article explores two methods for achieving this: using dot notation and square bracket notation.
Using Dot Notation
This method is straightforward when you know the property name you want to add. The syntax is as follows:
obj.propertyName = value;
For example, to add a property key3 with value value3 to the object obj, we would write:
obj.key3 = "value3";
Using Square Bracket Notation
When the property name is not known in advance or is dynamically determined, square bracket notation becomes necessary. The syntax is:
obj["propertyName"] = value;
This method is useful when retrieving or setting properties based on a string key. For instance, the following code uses a function to retrieve property values based on a dynamic propertyName:
var getProperty = function (propertyName) { return obj[propertyName]; }; console.log(getProperty("key1")); // value1 console.log(getProperty("key2")); // value2 console.log(getProperty("key3")); // value3
Additional Notes
It's important to note that JavaScript arrays can also be created using either array literal notation or the Array constructor notation. The former is preferred for its concise syntax, while the latter offers more flexibility when working with arrays as objects.
The above is the detailed content of How Do I Add Key/Value Pairs to JavaScript Objects Using Dot and Bracket Notation?. For more information, please follow other related articles on the PHP Chinese website!