为什么我在此脚本中未定义

时间:2013-03-08 09:09:10

标签: javascript

尝试输出日期加上30天。我今天已经加载了脚本,它说当天“未定义”,脚本的其余部分都可以。 '未定义,2013年4月7日'。

这是我的剧本:

// handle the due date
var dayNames = new Array("Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday");
var monthNames = new Array("January","February","March","April","May","June","July", "August","September","October","November","December");    
var todayPlus30 = new Date();
todayPlus30.setDate(todayPlus30.getDate()+30)
var dateStr = (dayNames[todayPlus30.getDate()] + ", " + monthNames[todayPlus30.getMonth()] + " " +  todayPlus30.getDate()  + ", " +  todayPlus30.getFullYear());

$('#date').html(dateStr);

2 个答案:

答案 0 :(得分:1)

你的dayNames数组有7个元素,因此它包含来自dayNames [0] .. dayNames [6]的元素。

当你在这里引用它时:

dayNames[todayPlus30.getDate()]

您正在尝试访问未定义的dayNames [7]。那是因为todayPlus30.getDate()返回7(getDate()“返回月份的日期”(根据MDN)。

将其更改为:

dayNames[todayPlus30.getDay()]

获取一周中的某一天。

答案 1 :(得分:0)

对于一周中的(整数)日,您需要getDay,而不是getDate