简体   繁体   English

如何在不使用Break的情况下停止无限提示循环?

[英]How do I stop an infinite prompt loop without using Break?

I've created an infinite loop with a prompt in order to insert city names into an array as long as you wish, however I would like to stop this infinite loop whenever the user hits cancel in the prompt without using a break . 我创建了一个带有prompt的无限循环,以便将城市名称插入到array ,只要您希望,但是只要用户在prompt单击cancel而不使用break ,我都希望停止此无限循环。

<script>
    var cities = new Array(); 
    var i=0; 

while(i >= 0){ 
    i++; 
    cities[i] = prompt("Type a City");
    if (cities[i] == null) break; 
document.write("<tr> <td>" + i + "</td> <td>" + cities[i] + "</td> </tr>")  
</script>    

after

if (cities[i] == null) break; if(city [i] == null)中断;

What else could I add other than break ? 除了break我还能添加什么?

Thanks 谢谢

Just set i to -1 instead of break 只需将我设置为-1而不是中断

Below is the code: 下面是代码:

var cities = new Array(); 
var i=0; 

while(i >= 0){ 
    i++; 
    cities[i] = prompt("Type a City");
    if (cities[i] == null) {
       i = -1; 
    } else {
       document.write("<tr> <td>" + i + "</td> <td>" + cities[i] + "</td> </tr>");
    }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM