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

How Can I Add New Key-Value Pairs to a JavaScript Object?

Susan Sarandon
Release: 2024-12-11 19:06:11
Original
929 people have browsed it

How Can I Add New Key-Value Pairs to a JavaScript Object?

Adding New Key-Value Pairs to JavaScript Objects

In JavaScript, objects serve as containers for storing key-value pairs. To enhance these objects, you may need to add new fields.

Method 1: Dot Notation (Key Known)

var obj = {
    key1: value1,
    key2: value2
};
obj.key3 = "value3";
Copy after login

Method 2: Square Bracket Notation (Dynamic Key)

var obj = {
    key1: value1,
    key2: value2
};
obj["key3"] = "value3";
Copy after login

Distinction

Dot notation is preferable when the key name is known upfront. Square bracket notation provides flexibility when determining the key name dynamically.

Array Construction

Array Literal Notation:

var arr = [];
Copy after login

Array Constructor Notation:

var arr = new Array();
Copy after login

Both methods create an empty array in JavaScript.

The above is the detailed content of How Can I Add New Key-Value Pairs to a JavaScript Object?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template