"while loop" returns 意外 "undefined"

"while loop" returns unexpected "undefined"

抱歉,如果这是一个非常简单的问题,但我真的无法弄清楚。我必须简单地在屏幕上写下从 1 到 8 的数字,而不使用 for 循环。我尝试使用 while 循环,如下所示:

var y=1;
function scrie(y){
  while (y<=8){
    document.write(y + " ");
    y++;
  }
}

它确实显示了数字,但最后有一个 undefined,如下所示:


     1 2 3 4 5 6 7 8 undefined
</pre>
可能是什么问题呢?
提前谢谢你。

如果您使用 document.write() 调用 scrie 函数,它将在末尾打印 undefined,因为 scrie 函数不会 return 任何内容。

要解决该问题,只需删除外部 document.write() 调用,如下所示:

var y=1;
function scrie(y){
  while (y<=8){
    document.write(y + " ");
    y++;
  }
}

scrie(y);