Associative Arrays in JavaScript
Associative Arrays are special arrays where you can call the array element using key as string rather than using the index number. This makes it easier to retrieve the value from array. This article will guide you on creating Associative Arrays in JavaScript. The downside of creating Associative Arrays in JavaScript is that these aren’t as useful in a loop as JavaScript does not provide the features of accessing array element using string value.
Example - Creating Associative Array using Array Object
<script type="text/javascript"> var my_car= new Array(); my_cars["Ford"]="Icon"; my_cars["Mercedes"]="S3 Class"; my_cars["Hyundai"]="Accent"; var car_type=prompt("What type of car do you like?",""); if ((car_type=="Ford") || (car_type=="Mercedes") || (car_type=="Hyundai")) alert("I think you should get a(n) "+my_cars[car_type]+"."); else alert("I don't really know what you should get. Sorry."); </script>
Here i am creating an Associative array called mycar. It has three key namely Ford, Mercedes and Hyundai. So to access the value for a particular key i will be using my_car["Ford"]
Similarly you can also create Associative Arrays using Object Class
Example - Creating Associative Array using Object
<script type="text/javascript"> var my_cars= new Object() my_cars["Ford"]="Icon"; my_cars["Mercedes"]="S3 Class"; my_cars["Hyundai"]="Accent"; </script>
Related Post
Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.












































Comments
No comments yet.
Leave a comment