【问题标题】:Looping through a Javascript Function循环一个 Javascript 函数
【发布时间】:2013-03-04 17:16:09
【问题描述】:

我在弄清楚这一点时遇到了一些麻烦。我想循环所有月份一次,而不是像我现在的代码那样循环十二次。任何人都可以帮忙,还有更有效的方法来循环这个功能吗?

谢谢!

    window.onload = function() {
    getMonth();
};

 function getMonth()
{
var x="",i=0;
var month=Array();
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";

   while (i<12)
      {
      x=x  + month + "<br/>";
       i++;
       }
    document.getElementById("months").innerHTML=x;
    }

这是我的 jsfiddle 演示的链接http://jsfiddle.net/priswiz/LqEE6/

【问题讨论】:

标签: javascript arrays loops while-loop


【解决方案1】:

只需使用 Array .join 方法。

var x = month.join("<br />");

如果您使用x=x + month[i] + "&lt;br/&gt;";,您的代码将起作用

【讨论】:

    【解决方案2】:

    我假设您正在尝试按索引访问数组

    while (i<12)
    {
      x=x  + month[i] + "<br/>";
      i++;
    }
    

    目前,您正在打印月份的值。

    【讨论】:

      猜你喜欢
      • 2019-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      相关资源
      最近更新 更多