如何使用Javascript中的While循环获取月份返回

问题描述:

我正在学习JS,并且很难弄清楚这一点。我想问问你们有没有人能发现我的错误。我想用一个while循环来返回1月到12月的所有月份的名字而不使用数组,这可能吗?谢谢。如何使用Javascript中的While循环获取月份返回

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

for(var month=0; month < 11; month++) 

function getMonth(month) { 
    var monthName; 
    if (month == 11) { 
     monthName = "December"; 
    } 
    return monthName; 
} 

function getMonth() 
{ 
var x="",month=0; 
while (month<11) 
    { 
    x=x + month + "<br>"; 
    i++; 
    } 
document.getElementById("months").innerHTML=x; 
} 

http://jsfiddle.net/priswiz/xuJRc/

+4

你对阵列有什么影响 – 2013-03-20 21:45:17

没有一个数组:

function getMonth(month) { 
    switch(month){ 
    case 0: return "January"; 
    case 1: return "February"; 
    //... 
    case 11: return "December"; 
    default: return "Not a valid Month"; 
    } 
} 

但是那痛苦的方式做到这一点。

随着阵列:

function getMonth(month){ 
    var monthNames = [ "January", "February", "March", "April", "May", "June", 
    "July", "August", "September", "October", "November", "December" ]; 
    return monthNames[month]; 
} 

我不知道你想不阵列while循环做什么。你会迭代什么?

+0

while循环只是在满足某些条件时迭代。条件可能是计数器是否小于某个值,或者其他计算或逻辑。因此,虽然一个非常常见的用途是迭代数组索引,但还有很多其他用途。 – RobG 2013-03-20 23:09:51

+0

@RobG我知道你可以用它来做其他事情。但是,你会如何使用它来从数字中获取月份?这就是用例,除非你将它变成Rube-Goldberg算法,否则我无法看到在没有数组的情况下对这个问题使用while循环的理由 – 2013-03-20 23:37:21