Javascript JScript确认无限循环?

Javascript JScript确认无限循环?,javascript,Javascript,然而,循环并没有结束。在过去的30分钟里,我一直在思考这个问题,但都是徒劳的尝试。有什么想法吗?你的评论不正确 r=true不测试r是否为true;它将r赋值为true 您需要使用==运算符比较变量 或者您可以在(r)时编写,因为r本身已经是真的了 var setOfCats = {}; //an object while (r = true) //testing to see if r is true { var i = 0; setOfCats.i = prompt ("What's

然而,循环并没有结束。在过去的30分钟里,我一直在思考这个问题,但都是徒劳的尝试。有什么想法吗?

你的评论不正确

r=true
不测试
r
是否为
true
;它将
r
赋值为
true

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

或者您可以在(r)时编写
,因为
r
本身已经是真的了

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++
}

您正在将
r
设置为
true
每个循环迭代。您希望
while(r==true)
,或者只希望
while(r)

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

您应该使用以下工具执行while测试:

while (r = true)
或者更惯用:

while(r === true)
这应该起作用:

while(r)

为清楚起见,
r
setOfCats
应设置在
之外,而
声明:

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++
}

变量被提升到范围的顶部,所以我不知道这有什么关系。而
r
未在
声明中定义,而
声明中设置了删除
var
关键字将使
r
成为一个全局变量–哦!伊恩,是的,我今天学到了一些东西。谢谢更改答案以反映Ingo的评论。现在脚本不运行。您可能需要在开始时将r设置为true。这就解决了它!谢谢它测试
r
是否为
true
(truthy,此处)…测试赋值结果(此处恰好为
true
)。但它的全部意义都被破坏了,因为它在每次迭代时都将
r
设置为
true
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?");
}