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分钟里,我一直在考虑这个问题,徒劳无功。有什么想法吗?
答案 0 :(得分:5)
您的评论不正确。
r = true
不测试 r
是否为true
;它指定 r
成为true
。
您需要使用===
运算符比较变量。
或者你可以写while(r)
,因为r
本身已经是真的。
答案 1 :(得分:3)
while (r = true)
您将每个循环迭代设置为r
到true
。您想要while (r == true)
,或只是while (r)
。
答案 2 :(得分:1)
为清楚起见,r
和setOfCats
应设置在while
声明之外:
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?");
}
答案 3 :(得分: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++
}