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?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-14 20:09:15228browse

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

Adding Key/Value Pairs to JavaScript Objects

In JavaScript, objects are collections of key/value pairs. To add a new key/value pair to an existing object, there are two common approaches:

1. Dot Notation:

If the key is known beforehand, you can use dot notation to assign a new value to the object:

var obj = {
  key1: 'value1',
  key2: 'value2'
};

obj.key3 = 'value3';

2. Square Bracket Notation:

For dynamically generated keys or when the key name is not known in advance, square bracket notation can be used:

obj['key3'] = 'value3';

Both methods achieve the same result, creating a new key/value pair within the object. Dot notation is preferred when the key is known, while square bracket notation is used when the key is determined dynamically.

In addition to objects, JavaScript also has arrays, which are ordered collections of values. Arrays can be created using:

  • Array Literal Notation: var arr = [];
  • Array Constructor Notation: var arr = new Array();

Arrays can be accessed and modified using both index and key-based syntax:

// Array Index Syntax
arr[0] = 'element1';
arr[1] = 'element2';

// Array Key-Based Syntax
arr['0'] = 'element1';
arr['1'] = 'element2';

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