我是编程新手,我有一段代码,我正在努力理解它的行为。
var play = prompt('Do you want to play?');
var userInput = "";
if (play == 'yes')
do {
var word = prompt('Enter a word.');
var play2 = prompt('Do you want to play again?');
" " + word++;
}
while (play == 'yes');
console.log(userInput);

我不明白为什么循环没有结束。如果没有根据while循环输入yes
,它是否应该停止提示问题?
我不明白为什么用户输入没有写入console.log
。我试图将所有用户输入连接起来。
答案 0 :(得分:0)
OP使用“var play”创建一个变量,但之后你可以改变它(play =“whatever”)或者通过执行添加(play + =“whatever”)。
在循环中例如“var play2”创建一个名为play2的新变量,但之后什么都不做,因为你再也没有读过或写过它。
你永远不会真正改变游戏的价值,所以一旦输入循环就玩总是=是。
与用户输入相同,您创建变量但从不写入变量。你应该在循环中添加单词和空格。
你可能正在寻找更像这样的东西:
var play = prompt('Do you want to play?');
var userInput = "";
if (play == 'yes')
do {
var word = prompt('Enter a word.');
play = prompt('Do you want to play again?');
userInput += word + " ";
}
while (play == 'yes');
console.log(userInput);
(编辑以反映评论建议)