我想用JavaScript编写2019年的所有日期,日期和月份。通过使用3个功能。我只找到了我可以使用的1个函数,但没有弄清楚。任何人都有一些想法或提示吗?谢谢。
我需要一个NameOfTheMonths,NameOfTheWeekdays和DaysInAMonth函数。每种功能之一。函数中不应包含任何打印,所有打印均应与迭代结合进行。
document.writeln("Days in 2019 is:");
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
for (var i = 0; i<=months.length; i++)
{
for (var k = 1; k<=31; k++)
{
document.write(months[i]);
document.writeln(k);
}
}
function rightAdjust(x, size)
{
x = "" + x; // secure that x is a string
var noOfBlanks = size - x.length;
var blanks = "";
for (var i = 0; i < noOfBlanks; i++)
{
blanks = blanks + " ";
}
return blanks + x;
}
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var days;
days = DaysInAMonth(k);
for (var i = 0; i<=months.length; i++){
for (var k = 1; k<=days.length; k++)
{
document.write(months[i]);
document.writeln(days);
}
}
function DaysInAMonth(days)
{
var result;
if (months == [0])
{
return 31;
}
else if (months == [1])
{
return 28;
}
else if (months == [2])
{
return 31;
}
else if (months == [3])
{
return 30;
}
else if (months == [4])
{
return 31;
}
else if (months == [5])
{
return 30;
}
else if (months == [6])
{
return 31;
}
else if (months == [7])
{
return 31;
}
else if (months == [8])
{
return 30;
}
else if (months == [9])
{
return 31;
}
else if (months == [10])
{
return 30;
}
else if (months == [11])
{
return 31;
}
}
document.write(DaysInAMonth(1));
答案 0 :(得分:0)
在JavaScript中,我只会使用一个对象。
obj = {months:[
{name: "january", days: 31},
{name: "febuary", days: 28},
{name: "march", days: 31},
{name: "april", days: 30},
...
]}
并在具有工作日名称数组的对象上进行一些嵌套的forEach()
和for
循环,并在工作日名称的数组索引上进行MOD。
printyear(firstdayindex = 0) {
let days = ["mon","tues", "wed"....]
let currentday = firstdayindex;
obj.months.forEach((m) => {
for (int x = 1; x <= m.days; x++) { console.log(days[(currentday++)%7]+ x + m.name) }
})
}
但是,如果您真的想抽象出这些功能,我相信您可以执行以下操作:
NameOfTheMonths() {
let names = [];
obj.months.forEach(m => {names.push(m.name);
return names;})
}
NameOfTheWeekdays() {//just return an array of names }
DaysInAMonth(month) {obj.months.findIndex(m=>m.name===month).days}
有了关于具体应该做什么的更多信息,我可能可以添加更多,但是我个人将不执行这三个功能就去完成该任务,并且只对上面描述的对象进行操作,因为您唯一需要的输入就是一年的第一天是星期几。然后,您将需要做更多的工作才能从3个功能中将数据整理在一起。