Associative arrays in javascript?

I am currently creating a 3d array in js using the following:

var arr = [["name1", "place1", "data1"],
          ["name2", "place2", "data2"],
          ["name3", "place3", "data3"]];

I can access each element using arr [0] or arr [1]. But do I have access to them using this key: arr ["name1"] should give me the first one. Any suggestions? I think I'm looking for Hashmap functionality.

+3
source share
3 answers

The only way to do this is to wrap it in an object.

var arr = {
    name1 : ["name1", "place1", "data1"],
    name2 : ["name2", "place2", "data2"],
    name3 : ["name3", "place3", "data3"]
};
+3
source

Javascript is a prototype of a dynamic language. You can create objects and change their structure whenever you want.

var o = {name1: {place1: data1}, name2: {place2: data2}};

and access it:

o.name1

, , , ( Chrome, , .. a-la-dynamic dispatch from smalltalk). (, MooTools) - ,

+1

.

- JavaScript:

>> var names = new Array();
undefined

>> names["first"] = "Dotan";
"Dotan"

>> names["last"] = "Cohen";
"Cohen"

>> for ( key in names ) { console.log(key+" "+names[key]) }
undefined
first Dotan
last Cohen

, , 2012 , , ! :

>> names
Array [  ]

, ​​:

>> names.length
0

Therefore, this is not an associative array in the sense that JavaScript would support it if it were intended, but rather a workaround, which is often useful if for some reason the real JS object does not support what you need:

>> var names = {};
undefined

>> names.first = "Dotan";
"Dotan"

>> names.last = "Cohen";
"Cohen"

>> for ( key in names ) { console.log(key+" "+names[key]) }
undefined
first Dotan
last Cohen

>> names
Object { first: "Dotan", last: "Cohen" }

>> Object.keys(names).length
2
0
source

Source: https://habr.com/ru/post/1757872/


All Articles