Home >Web Front-end >JS Tutorial >How Do I Add Key-Value Pairs to JavaScript Objects?

How Do I Add Key-Value Pairs to JavaScript Objects?

Susan Sarandon
Susan SarandonOriginal
2024-12-15 01:51:10576browse

How Do I Add Key-Value Pairs to JavaScript Objects?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn