0
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 分钟里,我一直在思考这个问题,但徒劳无功。有任何想法吗?

4

4 回答 4

5

你的评论不正确。

r = true测试是否rtrue;它指定 r成为true

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

或者你可以只写while(r),因为r它本身已经是真的了。

于 2013-08-05T20:36:51.517 回答
3
while (r = true)

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

于 2013-08-05T20:36:54.323 回答
1

为清楚起见,rsetOfCatswhile声明之外设置:

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?");
}
于 2013-08-05T20:38:24.970 回答
0

您在 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++
}
于 2013-08-05T20:37:49.357 回答