为什么未定义出现在for循环的末尾? (JavaScript)的

时间:2015-03-07 14:03:44

标签: javascript if-statement for-loop

我已经写了这个函数for循环来显示提示的答案给出的数字,但每次出现循环时,它会显示数字,然后在结尾显示未定义的术语。有什么特别的原因吗?

function numbers(){
var i=2;
while(i<=20){
    document.write("This is the number "+i+"<br>");
    i+=2;
}
}

var age = 21;
var age = prompt("How old are you?");

if(age==21){
document.write(numbers());
}

1 个答案:

答案 0 :(得分:1)

因为您正在函数中打印数字,然后从行document.write(numbers());中的函数打印返回值。由于您的函数没有返回任何内容,因此它会打印undefined

相关问题