在Javascript中通过几个if语句运行While循环

时间:2013-03-21 20:36:30

标签: javascript loops if-statement while-loop

我目前正在学习Javascript并且想问我如何通过几个if语句运行while循环,这样我就可以在列表中显示12个月,我想我应该使用像

while(monthName < 10){

但我不确定如何将其纳入我的功能:

window.onload = function() {
document.getElementById("months").innerHTML = getMonth(0);
};

function getMonth(month) {
var monthName;
if (month == 0) {
    monthName = "January";
}
if (month == 1) {
    monthName = "February";
}
if (month == 2) {
    monthName = "March";
}
if (month == 3) {
    monthName = "April";
}
if (month == 4) {
    monthName = "May";
}
if (month == 5) {
    monthName = "June";
}
if (month == 6) {
    monthName = "July";
}
if (month == 7) {
    monthName = "August";
}
if (month == 8) {
    monthName = "September";
}
if (month == 9) {
    monthName = "October";
}  
if (month == 10) {
    monthName = "November";
}
if (month == 11) {
    monthName = "December";
}
return monthName;
} 

http://jsfiddle.net/priswiz/rUpsb/

我知道有更有效的方法可以做到这一点,比如使用数组,但是为了教育目的而要求while循环/计数器。

谢谢:)

4 个答案:

答案 0 :(得分:2)

我会建议一个数组:

var months = ['January','February','March'...];

然后您将能够使用索引返回:

for(var i=0, max=months.length; i<max; i++){

     // You could have an if statement in here to do any checks...
     console.log(months[i]); // Just prints to console
}

答案 1 :(得分:1)

这将是一个更短的解决方案

var months = ["jannuary", ..., "Dezember"];

function getMonth(monthNumber){
    return months[monthNumber];
}

function getAllMonthsNames(){
    return months.join(", ");
}

我希望它有所帮助

答案 2 :(得分:1)

window.onload = function() {
  var current = 0;
    var html = '';
    while(current < 12){
      html += getMonth(current++) + '<br />';        
    }
  document.getElementById("months").innerHTML = html;
};

function getMonth(month) {
var monthName;
if (month == 0) {
    monthName = "January";
}
if (month == 1) {
    monthName = "February";
}
if (month == 2) {
    monthName = "March";
}
if (month == 3) {
    monthName = "April";
}
if (month == 4) {
    monthName = "May";
}
if (month == 5) {
    monthName = "June";
}
if (month == 6) {
    monthName = "July";
}
if (month == 7) {
    monthName = "August";
}
if (month == 8) {
    monthName = "September";
}
if (month == 9) {
    monthName = "October";
}
if (month == 10) {
    monthName = "November";
}
if (month == 11) {
    monthName = "December";
}
return monthName;
}   

http://jsfiddle.net/rUpsb/1/

答案 3 :(得分:1)

我会给你一些先进的解决方案,但是如果你明白了,你会从中学到很多......

  1. 创建一个月数= var months['January','February',....]
  2. 的数组
  3. 现在获取一个元素: var month = months [x];
  4. 以有效的方式返回所有元素:

    这里我们克隆月份数组,以便我们有原始

    的副本

    var clonedArray = months.clone();

    接下来我们要反转我们的数组,这样我们就有了最后一个元素

    <强> clonedArray.reverse();

    接下来我们简单地一次弹出一个元素(pop首先获取最后一个元素,这就是我们颠倒数组的原因,这样我们用pop获得的第一个元素是1月而不是Decemeber

    while(clonedArray){
       var month = clonedArray.pop();
       // Do your stuff with month
       $('#yourListId').append($('<li/>').html(month));
    }

  5. 在最后一行我使用jQuery,它只是意味着... getElementById('yourListId')并添加一个值为月的新列表项