如何在javascript中交替使用2个循环?

时间:2017-03-02 10:45:20

标签: javascript loops

我有两个循环。我怎么能交替运行它们? 例如,此代码的输出:

for (var i = 15; i >= 10; i--) {
  console.log(i)      
}
for (var t = 15; t <= 20; t++) {
  console.log(t)
}

将是:

15 // first loop started
14
13
12
11
10 // first loop ended
15 // second loop started
16
17
18
19
20 // second loop ended

如何获得此输出:

15 //first loop started
15 //second loop started
14 //first 
16 //second
13 //first
17 //second
12 //first
18 //second
11 //first
19 //second
10 //first loop ended
20 //second loop ended

1 个答案:

答案 0 :(得分:3)

您可以将初始化条件最终表达式部分放在一个for循环中。

for (var i = 15, t = 15; i >= 10 && t <= 20; i--, t++) {
    console.log(i)      
    console.log(t)
}