输出应该看起来像“Tuesday, July 26, 2016”,然后是“enjoy”,但是,它看起来像 “周二 七月 未定义,未定义 26 , 2016 星期二”
这是我的代码: var 今天 = new Date();
function getMonth1(today) {
if(today.getMonth() == 0) {
console.log("January");
}
else if(today.getMonth() == 1) {
console.log("February");
}
else if(today.getMonth() == 2) {
console.log("March");
}
else if(today.getMonth() == 3) {
console.log("April");
}
else if(today.getMonth() == 4) {
console.log("May");
}
else if(today.getMonth() == 5) {
console.log("June");
}
else if(today.getMonth() == 6) {
console.log("July");
}
else if(today.getMonth() == 7) {
console.log("August");
}
else if(today.getMonth() == 8) {
console.log("September");
}
else if(today.getMonth() == 9) {
console.log("October");
}
else if(today.getMonth() == 10) {
console.log("November");
}
else if(today.getMonth() == 11) {
console.log("December");
}
}
function getWeekday(today) {
if(today.getDay() == 0) {
console.log("Sunday");
}
else if(today.getDay() == 1) {
console.log("Monday");
}
else if(today.getDay() == 2) {
console.log("Tuesday");
}
else if(today.getDay() == 3) {
console.log("Wednesday");
}
else if(today.getDay() == 4) {
console.log("Thursday");
}
else if(today.getDay() == 5) {
console.log("Friday");
}
else if(today.getDay() == 6) {
console.log("Saturday");
}
}
function getDate1(today) {
console.log(getWeekday(today) + "," + getMonth1(today), today.getDate(), ",", today.getFullYear());
if(getWeekday(today) == "Tuesday") {
console.log("enjoy");
}
}
getDate1(今天);
最佳答案
除了必须像 Jaromanda X 提到的那样返回一个值之外,您还可以像这样简化代码(如 Touffy 提到的数组查找):
function getWeekDay(index) {
return
["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][index];
}
然后使用getDay()
调用它:
alert(getWeekDay(new Date().getDay()));
然后使用 getMonth()
调用它,对月份进行类似的设置。
关于javascript - 为什么输出应该去到 "undefined"项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38603677/