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

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

DDD
Release: 2024-12-16 21:48:10
Original
165 people have browsed it

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

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";
Copy after login

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";
Copy after login

Notably, this can be useful in situations where the property name is derived from a variable, for example:

var property = "key3";
obj[property] = "value3";
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template