简体   繁体   中英

Storing key value pair in javascript

Can we store key value pair in javascript in this way? array variable arr;

arr[key1]={value11,value12,value13...}
arr[key2]={value21,value22,value33...}

example:

arr["class"]={8,9,10}
arr["section"]={a,b,c}

and so on...

I am new to javascript.

To store a series or ordered list of values that you're going to index numerically, you'd typically use an array . So for instance, [8, 9, 10] is an array with three entries (the numbers 8 , 9 , and 10 ).

To store a keyed set of values, you'd usually use an object (if the set of key/value pairs is reasonably consistent and the keys are strings¹) or a Map (if the set of key/value pairs varies over time, or keys are not strings).

Example of an object with an array of numbers:

const obj = {
    class: [8, 9, 10]
};

or building it up:

const obj = {};
obj.class = [8, 9, 10];
// or
// obj["class"] = [8, 9, 10];

In this case, the key/value pairs are called properties of the object.

Or with a Map :

const map = new Map();
map.set("class", [8, 9, 10]);

In this case, the key/value pairs are called entries of the map.


¹ Technically objects can also have properties keyed by Symbols, but that's not usually something you have to deal with when first getting started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM