Listing 8.05 - Passing an array to a function
JS Bin
var getVisitorReport = function (visitorArray, dayInWeek) {
var days = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday"
];
var index = dayInWeek - 1;
var visitorReport;
visitorReport = "There were ";
visitorReport += visitorArray[index];
visitorReport += " visitors ";
visitorReport += "on " + days[index];
return visitorReport;
};
var visitors = [ 354, 132, 210, 221, 481 ];
var report = getVisitorReport(visitors, 2);
console.log(report);
Listing 8.05 - Passing an array to a function - Task 2
- Update the function to include Saturday and Sunday.
var getVisitorReport = function (visitorArray, dayInWeek) {
var days = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
];
var index = dayInWeek - 1;
var visitorReport;
visitorReport = "There were ";
visitorReport += visitorArray[index];
visitorReport += " visitors ";
visitorReport += "on " + days[index];
return visitorReport;
};
var visitors = [ 354, 132, 210, 221, 481, 1221, 1380 ];
var report = getVisitorReport(visitors, 2);
console.log(report);
Listing 8.05 - Passing an array to a function - Tasks 3&4
- Write a new function with three parameters, the month array, the week wanted and the day wanted. The new function should return the visitor report specified. You can call getVisitorReport from your function if you want.
- Create four arrays of week visitor numbers and a month array of the four weeks. Test your function for different weeks and days.
var getVisitorReport = function (visitorArray, dayInWeek) {
var days = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
];
var index = dayInWeek - 1;
var visitorReport;
visitorReport = "There were ";
visitorReport += visitorArray[index];
visitorReport += " visitors ";
visitorReport += "on " + days[index];
return visitorReport;
};
var getVisitorReportInMonth = function (monthArray, weekInMonth, dayInWeek) {
var weekArray = monthArray[weekInMonth - 1];
return getVisitorReport(weekArray, dayInWeek) + " of week " + weekInMonth;
};
var visitors = [
[ 354, 132, 210, 221, 481, 1221, 1380 ],
[ 288, 110, 178, 204, 380, 1090, 1173 ],
[ 290, 128, 187, 218, 380, 1128, 1201 ],
[ 469, 325, 348, 400, 620, 1629, 1402 ]
];
console.log(getVisitorReportInMonth(visitors, 1, 2));
console.log(getVisitorReportInMonth(visitors, 2, 3));
console.log(getVisitorReportInMonth(visitors, 3, 4));
console.log(getVisitorReportInMonth(visitors, 4, 5));