首页  >  文章  >  web前端  >  循环:For 循环、While 循环、For...Of 循环、For...In 循环

循环:For 循环、While 循环、For...Of 循环、For...In 循环

PHPz
PHPz原创
2024-08-07 09:57:321120浏览

Loops: For Loops, While Loops, For...Of Loops, For...In Loops

循环的目的是重复某些功能。

某些类型的循环包括:

  • for 循环
  • while 循环
  • for...of 循环
  • for...循环

For循环

To 可以写一个简单的 for 循环,如下:

for (let i = 1; i <= 10; i++) {
  console.log(i); // prints numbers 1-10
}

要循环数组,我们可以执行以下操作:

const animals = ['lizard', 'fish', 'turtle'];

for (let i = 0; i < animals.length; i++) {
  console.log(i, animals[i]);
}
// 0 'lizard'
// 1 'fish'
// 2 'turtle'

我们也可以反向循环这个数组:

for (let i = animals.length - 1; i >= 0; i--) {
  console.log(i, animals[i]);
}

// 2 'turtle'
// 1 'fish'
// 0 'lizard'

我们还可以在循环中循环:

for (let i = 0; i <= 2; i++) {
  for (let j = 0; j < 2; j++) {
    console.log(`i=${i}, j=${j}`);
  }
}

// i=0, j=0
// i=0, j=1
// i=1, j=0
// i=1, j=1
// i=2, j=0
// i=2, j=1

如果我们想要迭代数组的数组,这非常有用:

const seatingChart = [
  ['Abigale', 'Tim', 'Cynthia'],
  ['Bob', 'Carter', 'Zane', 'Tanja'],
  ['Quin', 'Xavier'],
];

// To print each name individually from seatingChart:
for (let i = 0; i < seatingChart.length; i++) {
  for (let j = 0; j < seatingChart[i].length; j++) {
    console.log(seatingChart[i][j]);
  }
}

While 循环

简单 while 循环的示例是:

let num = 0;

// to print out 0 through 4:
while (num < 5) {
  console.log(num);
  num++;
}

中断关键字

break 关键字可用于退出 while 循环:

let input = prompt('Say something:');
while (true) {
  input = prompt(input);
  if (input === 'stop copying me') {
    break; // finally stops prompting user
  }
}

它也可用于退出 for 循环。假设我们有这样一行:

let line = ['Abby', 'Salvia', 'Jamie', 'Carter', 'John'];

我们想要输出 Jamie 之前的每个人,但不输出 Jamie:

for (let i = 0; i < line.length; i++) {
  if (line[i] === 'Jamie') break;
  console.log(line[i]);
}

For...Of 循环

如果我们想打印数组中的每个值,我们可以这样做:

let people = ['Agitha', 'Bruce', 'Charlie', 'Dane', 'Ernie'];
// to print each persons name:
for (let person of people) {
  console.log(person);
}

为了使之前的座位表示例更加清晰,我们可以这样做:

const seatingChart = [
  ['Abigale', 'Tim', 'Cynthia'],
  ['Bob', 'Carter', 'Zane', 'Tanja'],
  ['Quin', 'Xavier'],
];

// To print each name individually from seatingChart:
for (let row of seatingChart) {
  for (let person of row) {
    console.log(person);
  }
}

For...In 循环

如果我们想迭代对象中的每个键值对,我们可以这样做:

const testScores = {
  jim: 34,
  abby: 93,
  greg: 84,
  mark: 95,
  melvin: 73,
};

for (let person in testScores) {
  console.log(`${person} scored ${testScores[person]}`);
}

如果我们想使用 For...Of 获得 testScores 的平均值,我们可以这样做:

let total = 0;
let scores = Object.values(testScores);
for (let score of scores) {
  total += score;
}
let avg = total / scores.length;
console.log(avg);

以上是循环:For 循环、While 循环、For...Of 循环、For...In 循环的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn