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
Susan SarandonOriginal
2024-12-11 19:06:11930browse

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";

Method 2: Square Bracket Notation (Dynamic Key)

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

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 = [];

Array Constructor Notation:

var arr = new Array();

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!

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