如何调用数组的字符串来显示

时间:2014-12-03 16:28:59

标签: javascript arrays

我有一个如下编码的下拉列表:

  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";

我的问题是,如果用户选择了无效日期(9月31日),并且#34; 9月没有31天,我需要提醒!",但目前它说& #34;第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); 

2 个答案:

答案 0 :(得分:4)

就像你指定它一样调用它:

如果

month[8]="September";

然后

alert("Month "+ month[8] +" doesn't have 31 days!");

会提醒月份的名称(月份9月没有31天!

修改

根据您的评论,似乎您正在为数组列表和所选月份数字使用变量名month ...

你需要改变它。我建议将数组更改为months

var months = new Array(12);

months[0]="January"; 
months[1]="February";
...

然后,调用它将选定的month作为索引传递:

alert("Month "+ months[month] +" doesn't have 31 days!")

答案 1 :(得分:0)

我们假设您的数组变量名为months。在这种情况下,您可能希望使用:

alert("Month " + months[month - 1] + " doesn't have 31 days!");

由于常规月份为1-12,因此您必须考虑到一个错误。