WBxs
Jan 29, 2018

Welcome to our tutorial, now I am going to explain how to create javascript associative array with an example.

protect your javascript code

By the end of this tutorial you will be aware of:

What is a Javascript Associative Array ?

Several programming languages allow arrays with named indexes. Arrays whose elements are set with named indexes rather than by numeric indexes are called associative arrays (or hashes). JavaScript does not allow arrays with named indexes, where arrays always use numbered indexes. Although that, javaScript objects are used in similar manner with named indexes which will be referred to as " associative array " below.

How to Create Javascript Associative Array ?


To create an associative array, define a block of elements in a json form. Simply, the json form declares elements in-between curly braces and, for each element, key is set on left and contents on right of a colon (:).
var fruits = {"yellow": "banana",
"red": "apple",
"orange": "orange",
"green": "mango"};

How to Get Value by Key in a Javascript Associative Array ?


To get a specific element of an associative array, you can choose a key explicitly, as follow:
//in this case outputting the value “apple”

document.write(fruits['red']);
//Or

document.write(fruits.red);

Example on a Javascript Associative Array


Next example shows how you might create an associative array to store the contents of the “fruits” array with keys of their colors.
<script>
//Creating and displaying an associative array

var fruits = {"yellow": "banana",
"red": "apple",
"orange": "orange",
"green": "mango"};
for (fruit in fruits)
document.write(fruit + " = " + fruits[fruit] + "<br />");
</script>

To check that the array has been created and filled correctly, you can use another kind of for loop using the " in " keyword. This creates a new variable to use only within the array ("fruit" in above example) and iterates through all elements of the array that is on right of the " in " keyword ("fruits" in above example). The loop acts on each element of "fruits", changing the key value into "fruit".


Using the key value stored in "fruit", you can get the value of the current element of fruits. The result of running the example script in a browser is as follows:
yellow = banana
red = apple
orange = orange
green = mango

Try WhiteBoxes JavaScript Obfuscator >>

Thank you for reading the above article. Please let us know your comments below.

References:
  • Practical Experience
About the author

Adam Hassan

Adam is a freelance web designer, recreational software developer, author and CEO of infoapper.com . Also, has passion to learn and transfer the know-how of every valuable thing.
Views: 794
× Close
Results:
Want to Enable Key Features? Create a Free Account.