Looping Through JavaScript Associative Array

Create your array so that it follows the following format:

var weekdays = {"MON" : "monday", "TUES" : "tuesday", "WED": "wednesday", "THURS" : "thursday", "FRI" : "friday"};

*Note the use of curly braces instead of square brackets and also the colon instead of =>

Then to loop through this associative array:

for (var day in weekdays) {
  document.write( day + " : " + weekdays[day] + "<br />" );
}

Here, the variable ‘day’ represents each individual key in the array ‘weekdays’. The loop will run through each key and stop after the last one is completed.

Your output:

KEY : value

MON : monday
TUES : tuesday
WED : wednesday
THURS : thursday
FRI: friday
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s