Get Programming with JavaScript - Listing 8.04
Listing 8.04 - Using a variable as an index
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
var dayInWeek = 4;
console.log( days[dayInWeek] );
console.log( days[dayInWeek - 1] );
Further Adventures
Listing 8.04 - Using a variable as an index - Task 1
- Change the value of the dayInWeek variable to display a different day.
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
var dayInWeek = 2;
console.log( days[dayInWeek] );
console.log( days[dayInWeek - 1] );
Listing 8.04 - Using a variable as an index - Task 2
- Write a function that accepts a number for the day of the week to be displayed and returns the day as a string.
- Assign the function to a getDay variable.
var getDay = function (dayNumber) {
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
return days[dayNumber - 1];
};
You could use Math.max and Math.min to make sure the dayNumber matches an element in the days array.
var getDay = function (dayNumber) {
// dayNumber should be at least 1
dayNumber = Math.max(1, dayNumber);
// dayNumber must not exceed the number of days in the array
dayNumber = Math.min(days.length, dayNumber);
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
return days[dayNumber - 1]; // the index is zero-based
};
Listing 8.04 - Using a variable as an index - Task 3
- Call your function, passing it 4 as the day of the week.
- Log the value it returns.
var getDay = function (dayNumber) {
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
return days[dayNumber - 1];
};
var dayInWeek = 4;
console.log( getDay(dayInWeek) );