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 rtrue

演算子を使用して変数を比較する必要があります。===

または、それ自体がすでに 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 に答える