Javascript 提示循环中的备选方案

Javascript prompt alternative in Loop

因此,我可以使用 <input type="text">button 来处理按钮单击时输入的值,而不是提示,例如:

var x = [];

$('button').on('click', function(){
  x.push($(input[type="text"]).val());  
});

但是,在一个循环中,例如:

var y=0;
var z=[];
do {
  z.push(prompt('input value'));
  y++;
}
while (y<5);

循环会提示输入一个值,用户输入值,提示将值赋给数组,然后循环会再次提示,直到 y 达到 5。

我想用我的文本字段输入和按钮来代替提示。我怎样才能让循环暂停,等待用户输入文本,并在每次到达循环的那个部分时通过单击按钮提交?

编辑:将 5 个值推入数组只是一个示例。假设我想创建一个游戏,其中循环将随着 "up" 向上移动并随着 "down" 输入向下移动。我希望能够在循环期间请求用户输入,类似于提示的方式,但不使用提示。

你不知道。你完全改变了你的逻辑,完全失去了循环:

var z = [];
$('button').on('click', function() {
    z.push($(input[type="text"]).val());
    if (z.length === 5) {
        // Do what you would have done after the end of the loop here
    }
});

您已编辑问题并在下方评论说您接下来的操作可能会因输入而异。这不是问题,您只需将事件响应模型应用于您的新需求。比如你说

...Let's say I wanted to create a game where the loop would move up with an "up" and down with a "down" input.

然后:

$('button').on('click', function() {
    switch ($(input[type="text"]).val().toLowerCase()) {
        case "up":
            // Do the "up" thing
            break;
        case "down":
            // Do the "down" thing
            break;
    }
});

有几种不同的方式可以处理调度,不一定是 switch。例如:

var actions = {
    up: function() {
        // Do the "up" thing
    },
    down: function() {
        // Do the "down" thing
    }
};
$('button').on('click', function() {
    var action = actions[$(input[type="text"]).val().toLowerCase();
    if (action) {
        action();
    }
});

等等。关键是,而不是迭代工作(我做这个,我得到那个输入,我做下一件事,我得到更多的输入),你正在工作反应性:我得到输入,我做点什么。这可能需要某种超出上面所示的状态管理(记住你在哪里)(第一个例子有状态管理:我们检查 z 的长度以查看我们收集了多少输入)。