循环:For 循环、While 循环、ForOf 循环、ForIn 循环
时间:2024-08-07
浏览:243
作者:佚名
哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《循环:For 循环、While 循环、ForOf 循环、ForIn 循环》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

循环的目的是重复一些功能。
一些类型的循环包括:
- 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 循环、ForOf 循环、ForIn 循环》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
