This snippet should print the number of days in a month specified through user input. However, each day is logged twice to the console, regardless which month is chosen:
"Day:", 1
"Day:", 1
"Day:", 2
"Day:", 2
var month = prompt("enter which month of the year 1 to 12", 6);
for (var days = 1; days <= 31; days ) {
if ((month == 4 || month == 6 || month == 9 || month == 11) && days == 31) continue
console.log('Day:', days);
if (month == 2 && days == 28) break
console.log('Day:', days);
}
CodePudding user response:
var month=prompt ("enter which month of the year 1 to 12", 6);
for(var days=1; days<=31; days ) {
if((month==4 || month==6 || month==9 || month==11) && days==31)break;
if(month==2 && days==28)break
console.log('Day:',days);
}
CodePudding user response:
but my output print twice in console like day1 repeats twice
Without {}
, if
statements only affect the immediately following line which in this case would be just continue
and break
as you have set them inline.
I think the program can be improved to factor in for the leap year value.
var month = prompt("enter which month of the year 1 to 12", 6);
if (month < 1 || month > 12) {
alert('Please enter a valid month');
}
// to factor for the leap year instead of hardcoding 28 for Feb
var currentYear = new Date().getFullYear();
var daysInMonth = new Date(currentYear, month, 0).getDate();
for (var days = 1; days <= daysInMonth; days ) {
console.log('Day:', days);
}