0

The Date Object JavaScript

I was able to get the day of the week but I'm not sure how to get rid of "undefined" behind it. The program you are given takes year, month and day as input. Create a function that takes them as arguments and returns the corresponding day of the week. Sample Input 1993 7 12 Sample Output Thursday Hint: The given code creates a Date object from the parameters. Use the getDay() method of the date object to get the index, then use it in the given names array to return the name of the day. ---------------------------------------------------------------------------------------------------- This is my code: function main() { var year = parseInt(readLine(), 10); var month = parseInt(readLine(), 10); var day = parseInt(readLine(), 10); //var dayOfWeek; console.log(getWeekDay(year,month,day)); //console.log(getWeekDay(dayOfWeek)); } function getWeekDay(year, month, day) { var names = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var d = new Date(year, month, day); //complete the function var year = d.getFullYear(); var month = d.getMonth(); var day = d.getDay(); //var names = names[day]; var dayOfWeek = names[day]; console.log(dayOfWeek); //console.log(year + "," + month + "," + day); }

5th Nov 2021, 11:28 PM
Kianna Hendricks
Kianna Hendricks - avatar
3 ответов
+ 3
function main() { var year = parseInt(readLine(), 10); var month = parseInt(readLine(), 10); var day = parseInt(readLine(), 10); console.log(getWeekDay(year, month, day)); } function getWeekDay(year, month, day) { var names = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var d = new Date(year, month, day); //complete the function return names[d.getDay()]; }
7th Dec 2021, 7:24 AM
Peter Coker
Peter Coker - avatar
+ 1
You got 2 outputs. One from main - undefined and one correct from getWeekDay. You need to return value from getWeekDay function and than log inside main, and you will got only one correct output. Reason is in main you call function inside console log and log its value console.log(getWeekDay(year,month,day)) but this function dont return value so default is undefined, thats why you got both
5th Nov 2021, 11:56 PM
PanicS
PanicS - avatar
0
function main() { var year = parseInt(readLine(), 10); var month = parseInt(readLine(), 10); var day = parseInt(readLine(), 10); console.log(getWeekDay(year, month, day)); } function getWeekDay(year, month, day) { var names = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var d = new Date(year, month, day); //complete the function var weekday = d.getDay(); return names[weekday]; }
25th Oct 2022, 12:38 PM
nDrew
nDrew - avatar