组合for循环,改为“while循环”,保持功能

时间:2016-11-17 22:21:11

标签: javascript loops for-loop

有没有一种简单的方法可以将这三个循环合二为一?然后将它们更改为“while循环”,同时保持相同的功能?

我已尝试将数据切换为:

{ run = true; counter = 1; while (run == true) /* or while (run) */ {document.write (counter);
counter++; if (counter > 3) run = false; } // end loop /* How many times will this loop go? */ }

但只能得到一个空白页。

这是原始的“for loop”代码;

//numbers divisible by 5
for (i=1; i<=50; i++)  {
if (i%5 == 0) document.write ("number divisible by five is:  " + i + "<br />") ;
} //for
document.write  ("========================<br />");  //seperator

//numbers divisible by 7
for (i=1; i<=50; i++)  {
if (i%7==0) && (i%2!=0) ) document.write ("number divisible by seven is:  " + i + "<br />") ;
} //for
document.write  ("========================<br />");  //seperator

//numbers divisible by 9
for (i=1; i<=50; i++)  {
if (i%9==0) && (i%2==0) ) document.write ("number divisible by nine is:  " + i + "<br />") ;
} //for
document.write  ("========================<br />");  //seperator

2 个答案:

答案 0 :(得分:0)

如果要组合循环,请将三个if语句放入从1到50的单个循环中。

要将for循环转换为while循环,直接翻译就是这样

 i = 1;  // variable 
while ( i<=50)  {  // condition 
    if (i%5 == 0) document.write ("number divisible by five is:  " + i + "<br />") ;
    // more if statements 
    i++;  // increment 
 } 

答案 1 :(得分:0)

也许试试这个?

var divisions = {
    five: [],
    seven:[],
    nine: []
};

for(i = 1; i <= 50; i ++;){
    if(i % 5 == 0) divisions.five.push(i);
    if((i % 7 == 0) && (i % 2 != 0)) divisions.seven.push(i);
    if((i % 9 == 0) && (i % 2 == 0)) divisions.nine.push(i);
}

divisions.five.forEach(function(number){
    document.write('number divisible by 5 is:' + number);
});

document.write  ("========================<br />");  //seperator

divisions.seven.forEach(function(number){
    document.write('number divisible by 7 is:' + number);
});

document.write  ("========================<br />");  //seperator

divisions.nine.forEach(function(number){
    document.write('number divisible by 9 is:' + number);
});

document.write  ("========================<br />");  //seperator

我没有测试过这个,在这里的文本框中写道,你应该得到一般的想法。