1

当遇到用户输入错误时,我试图让我的循环重新启动。我需要它从一开始就重新启动,而不仅仅是最后一个问题。

所以下面当它说validImput = false时,这就是我试图让它重新启动的地方。

{
var validInput = true;
var start = confirm('Add item to shoping cart');
if (start == true) {

    // ask first question
    var orderProductCodeArr = parseInt(prompt('Enter input: '), 10);

    if (isNaN(orderProductCodeArr)) {
        alert("input is not a valid number");
        validImput = false

    } else if (orderProductCodeArr < 0 || orderProductCodeArr >= PRODUCT_LIST.length) {
        alert("code does not match any item");
        validInput = false;
    }

    // ask second question

     else if(validInput == true) {
        var item = PRODUCT_LIST[orderProductCodeArr];
        alert("item is: " + item);
    }
        // get quantity input


    var quanityArr = parseInt (prompt('Enter quality amount'),10);
        if (isNaN(quanityArr)) {
        alert("input is not a valid number");
        validInput = false;

    }




} else {
    document.writeln('still to come')
}

}

4

2 回答 2

0

尝试

function test()
{

   for(var s=0;s<5;s++)
   {
    try
    { 

     //body of the for loop

    }catch(e){s=0;}
   }

}
于 2013-04-15T05:38:15.093 回答
0

重新开始的常用方法是某种循环结构,通常使用while如下:

while (true) {
    // your loop code here

    // you can use break; to break out of the while loop 
    //     anywhere to stop repeating
    // you can use continue; to jump to the next iteration immediately

}

或者,有时您使用这样的循环条件:

var doAgain = true;
while (doAgain) {

    // within the loop, you set doAgain to false when you are done
    // and don't want to repeat the loop again

}
于 2013-04-15T05:58:42.890 回答