JS Associative Array


Associative array initialization:

//define while initialization
var arr = {"city" : "New York", "country" : "USA"};
//define dynamically
var arr = new Array();
arr["city"] = "New York";
arr["country"] = "USA";


Normal array use 0 - array.length to index the array:

var narr = ["ta","az","tx","cn"];
var x = narr[0]; //x="ta"
var y = narr[1]; //y="az"


Associative array use string as its index:

var arr = {"city" : "New York", "country" : "USA"};
var x = arr["city"]; //x = "New York"


length property can be used to get the associative array size:

var arr={"a" : "2", "d" : "5", "h" : 3, "u" : 1};
alert(arr.length); //4


for in loop can be used to iterate through the associative array:

var arr = {"city" : "New York", "country" : "USA"};
for (indx in arr)
{
var val = arr[indx];
alert(indx + ": " + val);
}


break, continue can be used to jump out or skip 1 step of the loop:

var arr={"a" : "2", "d" : "5", "h" : 3, "u" : 1};
for (indx in arr)
{
if (indx == "h") break;
var val = arr[indx];
alert(indx + ": " + val);
}
for (indx in arr)
{
if (indx == "h") continue;
var val = arr[indx];
alert(indx + ": " + val);
}


Define a dimensional associative array dynamically.

var efs = new Array();
efs["em"]=new Array();
	efs["em"]["em"] = 1;
	efs["em"]["g5"] = 1899.10078;
	efs["em"]["xy"] = 1000;
	efs["em"]["d5"] = 1;
efs["g5"]=new Array();
	efs["g5"]["em"]=0.0005;
	efs["g5"]["g5"]=1;
	efs["g5"]["xy"]=0.5265;
	efs["g5"]["d5"]=0.0005265;
efs["em"]["xy"]; //1000


endmemo.com © 2024  | Terms of Use | Privacy | Home