JavaScript for循环执行

时间:2014-02-07 09:52:06

标签: javascript

我写了一个程序,用javascript中的特定输出:

  

i = 2 j = 1

     

i = 3 j = 2

     

i = 1 j = 3

     

i = 2 j = 1

     

i = 3 j = 2

     

i = 1 j = 3

依旧......

但是下面的代码永远不会产生我需要的输出。

c=2;
for (i=c; i<=3; i++){
    alert(i);

    if(i==1){
       j=3;
    }else{
       j=j-1;
    }

    alert(j);

    if(i==3){
        c=1;
        continue;
    }
}

2 个答案:

答案 0 :(得分:0)

这似乎是一个简单的问题:你只需要用2个变量(i和j)计算1比1,差异就是你不从1开始。

你需要同时增加j和i。

// this for not making infinite loop
var nb_loop=0;
var max_loop=10; 
var j=0;
for (var i=2; i<=3 ; i++){
  nb_loop++;
  j++;
  console.log("i="+i+", j="+j); // or alert if you want
  if (j>=3)
    j=0;
  if (i>=3)
    i=0;
  if (nb_loop>max_loop)
    break; 
}

注意:while循环可能比“for”

更好

答案 1 :(得分:0)

我不知道你是否需要使用它,我重现你的输出(见控制台

var c=1,
    j = 2,
    i = 0,
    x = 2; // this a limit for loop to prevent infinite loop

for (c; c<=3; c++){
    if(c == 1){
        i = 2;
    }else if(c == 2){
        i = 3;
    }else{
        i = 1;
    }

    //alert("i="+i+" j="+c); uncomment to see alert
    console.log("i="+i+" j="+c);

    //you can change this condition to stop the loop where you need
    if(c==3 && x != 0){
        c = 1;
        x--;
    }
}

看到这个例子,也许可以帮助: http://jsfiddle.net/pvMby/1/

相关问题