我有一個下拉列表編碼是這樣的:如何調用數組的字符串顯示
var month=new Array(12);
month[0]="January";
month[1]="February";
month[2]="March";
month[3]="April";
month[4]="May";
month[5]="June";
month[6]="July";
month[7]="August";
month[8]="September";
month[9]="October";
month[10]="November";
month[11]="December";
我的問題是我需要的警報來了,如果一個用戶選擇了一個無效的日期(SEP 31)說「 9月沒有31天!「,但目前它說」9個月沒有31天!「。以下是代碼:
alert("Month "+month+" doesn't have 31 days!")
如何定位字符串名稱而不是數字?
編輯
完全更新的代碼:
function dispDate(dateObj) {
//array to change numbered date to string
var months=new Array(12);
months[0]="January";
months[1]="February";
months[2]="March";
months[3]="April";
months[4]="May";
months[5]="June";
months[6]="July";
months[7]="August";
months[8]="September";
months[9]="October";
months[10]="November";
months[11]="December";
//getting month,day and year from form
mon = months[dateObj.getMonth()];
day = dateObj.getDate();
day = (day < 10) ? "0" + day : day;
year = dateObj.getYear();
if (year < 2000) year += 1900;
//the format of displaed date
return (mon + " " + day+"," + " " + year);
}
//main function for all calculations
function isValidDate(){
//getting values from selected options
var SelectedDay = document.TestForm.firstDay_day.selectedIndex;
var day = document.TestForm.firstDay_day.options[SelectedDay].value;
var SelectedMonth = document.TestForm.firstDay_month.selectedIndex;
var month = document.TestForm.firstDay_month.options[SelectedMonth].value;
var SelectedYear = document.TestForm.firstDay_year.selectedIndex;
var year = document.TestForm.firstDay_year.options[SelectedYear].value;
//check for number of day in month
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
alert("Month "+ months[month] +" doesn't have 31 days!")
return false;
}
if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap)) {
alert("February " + year + " doesn't have " + day + " days!");
return false;
}
}
var dateStr=(month + "/" + day + "/" + year);
'month [8]'將被替換爲'September' – 2014-12-03 16:30:53
您的輸出沒有意義。你連接整個數組,但是然後說它給你*「第9個月沒有31天!」*。那麼'月'是什麼?一個數組或數字?代碼不夠。 – 2014-12-03 16:32:52
我懷疑他正在重複使用相同的變量名稱來處理兩個不同的事情:整個月份列表和所選月份編號。第二種用法是重寫第一種。 – Barmar 2014-12-03 16:34:28