
循环的目的是重复一些功能。
一些类型的循环包括:
- for 循环
- while 循环
- for…of 循环
- for…循环
for循环
to 可以写一个简单的 for 循环如下:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 
for(let i = 1; i 
 
 
 
 <p>要循环数组,我们可以执行以下操作:<br></p>
 
 <pre class="brush:php;toolbar:false">constanimals = ['lizard', 'fish', 'turtle'];
 
 for(let i = 0; i 
 
 
 
 <p>我们还可以反向循环这个数组:<br></p>
 
 <pre class="brush:php;toolbar:false">for(let i = animals.length - 1; i >= 0; i--) {
   console.log(i, animals[i]);
 }
 
 | 
 
我们还可以循环内循环:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 
for(let i = 0; i 
 
 
 
 <p>如果我们想要迭代数组的数组,这很有用:<br></p>
 
 <pre class="brush:php;toolbar:false">constseatingchart = [
   ['abigale', 'tim', 'cynthia'],
   ['bob', 'carter', 'zane', 'tanja'],
   ['quin', 'xavier'],
 ];
 
 for(let i = 0; i 
 
 
 
 <h2>
   
   
   while循环
 </h2>
 
 <p>简单 while循环的一个例子是:<br></p>
 
 <pre class="brush:php;toolbar:false">let num = 0;
 
 while(num 
 
 
 
 <h2>
   
   
   中断关键字
 </h2>
 
 <p>break关键字可用于退出while循环:<br></p>
 
 <pre class="brush:php;toolbar:false">let input = prompt('say something:');
 while(true) {
   input = prompt(input);
   if(input === 'stop copying me') {
     break; 
   }
 }
 | 
 
它也可以用于退出 for 循环。假设我们有一行:
| 1 | 
let line = ['abby', 'salvia', 'jamie', 'carter', 'john'];
 | 
 
我们想要输出 jamie 之前的每个人,但不输出 jamie:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 
for(let i = 0; i 
 
 
 
 <h2>
   
   
   for...of 循环
 </h2>
 
 <p>如果我们想打印数组中的每个值,我们可以这样做:<br></p>
 
 <pre class="brush:php;toolbar:false">let people = ['aGitha', 'bruce', 'charlie', 'dane', 'ernie'];
 for(let person of people) {
   console.log(person);
 }
 | 
 
为了使之前的座位表示例更清晰,我们可以这样做:
| 1 2 3 4 5 6 7 8 9 10 11 12 | 
constseatingchart = [
   ['abigale', 'tim', 'cynthia'],
   ['bob', 'carter', 'zane', 'tanja'],
   ['quin', 'xavier'],
 ];
 
 for(let row of seatingchart) {
   for(let person of row) {
     console.log(person);
   }
 }
 | 
 
for…in 循环
如果我们想迭代对象中的每个键值对,我们可以这样做:
| 1 2 3 4 5 6 7 8 9 10 11 | 
consttestscores = {
   jim: 34,
   abby: 93,
   greg: 84,
   mark: 95,
   melvin: 73,
 };
 
 for(let person in testscores) {
   console.log(`${person} scored ${testscores[person]}`);
 }
 | 
 
如果我们想使用 for…of 得到 testscores 的平均值,我们可以这样做:
| 1 2 3 4 5 6 7 | 
let total = 0;
 let scores = Object.values(testScores);
 for(let score of scores) {
   total += score;
 }
 let avg = total / scores.length;
 console.log(avg);
 |