How to use JavaScript dictionary

A JavaScript dictionary (also known as an object) is a data structure composed of key-value pairs that can be used to store and access data. The following is an example of adding, deleting, modifying and querying JavaScript dictionaries:

1. Add operation

New key-value pairs can be added to a JavaScript dictionary in the following ways:

```javascript

// Create an empty dictionary object

var dict = {};

// add key-value pair

dict["key1"] = "value1";

dict.key2 = "value2";

```

2. Delete operation

A key-value pair in a JavaScript dictionary can be removed by:

```javascript

// Create a dictionary object

var dict = {key1: "value1", key2: "value2"};

// delete the key-value pair

delete dict.key1;

```

3. Modify operation

Key-value pairs in JavaScript dictionaries can be modified in the following ways:

```javascript

// Create a dictionary object

var dict = {key1: "value1", key2: "value2"};

// Modify the key-value pair

dict.key1 = "new_value1";

```

4. Query operation

Key-value pairs in JavaScript dictionaries can be queried in the following ways:

```javascript

// Create a dictionary object

var dict = {key1: "value1", key2: "value2"};

// query key-value pairs

console.log(dict.key1); // output "value1"

console.log(dict["key2"]); // output "value2"

```

It should be noted that the keys in JavaScript dictionaries must be of string type, and the values ​​can be of any type. If you want to use other types of keys, you need to convert them to string type first.

 

Guess you like

Origin blog.csdn.net/weixin_59246157/article/details/129580827