JScript 确认无限循环

JScript confirm infinite loop?

本文关键字:无限循环 确认 JScript      更新时间:2023-09-26
var setOfCats = {}; //an object
while (r = true) //testing to see if r is true
{
  var i = 0;
  setOfCats.i = prompt ("What's your cat's name?", ""); //index object elements
  alert ("Congratulations! Your cat has been added to the directory.");
  var r = confirm ("Would you like to add another cat?"); //if r is true, then the loop should continue. if false, the loop should end.
  i++
}

但是,循环不会结束。在过去的30分钟里,我一直在思考这个问题,徒劳无功。有什么想法吗?

您的评论不正确。

r = true测试r是否true;它分配r成为true

您需要使用 === 运算符比较变量。

或者你可以写while(r),因为r本身已经是正确的。

while (r = true)

您正在设置rtrue每个循环迭代。 你想要while (r == true),或者只是while (r)

为清楚起见,应在while声明之外设置rsetOfCats

var setOfCats = [];
var r = true;
while (r) {
    setOfCats.push( prompt ("What's your cat's name?", "") );
    alert ("Congratulations! Your cat has been added to the directory.");
    r = confirm ("Would you like to add another cat?");
}

在每次迭代 while 表达式时,将 r 的值重新赋值为 true。 因此,它将始终覆盖该值。

您应该使用以下方法进行 while 测试:

while(r === true)

或更惯用:

while(r)

这应该有效:

var setOfCats = {}; //an object
var r = true;
while(r) //testing to see if r is true
{
    var i = 0;
    setOfCats.i = prompt ("What's your cat's name?", ""); //index object elements
    alert ("Congratulations! Your cat has been added to the directory.");
    r = confirm ("Would you like to add another cat?"); //if r is true, then the loop should continue. if false, the loop should end.
    i++
}