How can you create a multi dimensional array in javascript and grab the values without looping through them. I was thinking that maybe it would be something like this:
This looks so wrong to me and I’m sorta lost here. What I was originally trying to do is glossary where all I need to do is access the glossary term and definition. I was thinking you could do this with a common key/value pair but I’m not sure if JavaScript can support it. I only want to grab the individual term/definition then later on loop out the rest.
Do you really need a multi-dimensional associative array, or is something like this what you are looking for:
var myObject = {"dog":"a four legged animal", "human":"a two legged animal", "whale": "a big thing that lives in the ocean"};
var word = "human";
alert("Accessing one word in the glossary--\
\
" + word + ": " + myObject["human"]);
var str = "";
var property;
for(property in myObject)
{
str += property + ": " + myObject[property] + "\
";
}
alert("The whole glossary--\
\
" + str);
That’s pretty close to what I am looking for! Thanks!
I was just curious lets say I created a function that will grab the key/value pair based upon the term being passed so lets say that we had a function called:
showTermDefinition()
and we wanted to grab the human key/value pair how would we go about doing that?
so lets say the use of this function would be something like this:
showTermDefinition(“human”);
What would the code in the function be?
function showTermDefinition(term)
{
alert("Accessing one word in the glossary--\
" + term": " + myObject[term]);
}
Here’s an example of a multi-dimensional “thing” that might work for you:
var myObject = {};
myObject.Javascript = ["jstext0", "jstext1", "jstext2"]; //creates a Javascript property for myObject, and assigns it an array
myObject.PHP = ["phptext0", "phptext1", "phptext2"];
myObject.ColdFusion = ["cftext0", "cftext1", "cftext2"];
var category = "PHP";
var index_num = 0;
alert(myObject[category][index_num]);
var property
for(property in myObject)
{
for(var i = 0, len = myObject[property].length; i < len; i++)
{
alert(myObject[property][i]);
}
}
If you want to access the array with words rather than the index values 0,1,2, then assign an object to the property instead of an array: