JavaScript for…of 循环
在本教程中,您将了解如何使用 JavaScript for...of 语句来遍历可迭代对象。
JavaScript for…of 循环简介
ES6 引入一个新语句 for...of 来迭代可迭代对象,例如:
下面展示了 for...of 的语法:
for (variable of iterable) {
// ...
}variable
在每次迭代中,可迭代对象的一个属性被分配给 variable。您可以使用 var、let或 const 来声明 variable.
iterable
iterable 是一个对象,其 iterable 属性被迭代。
JavaScript for of 循环示例
遍历数组
下面的示例显示如何使用 for...of 循环访问数组的元素:
let scores = [80, 90, 70];
for (let score of scores) {
score = score + 5;
console.log(score);
}输出:
85
95
75在此示例中,for...of 迭代遍历 scores 数组的每个元素。它在每次迭代中将 scores 数组的元素分配给 score 变量。
如果你不改变循环内的变量,你应该使用 const关键字而不是 let 关键字,如下所示:
let scores = [80, 90, 70];
for (const score of scores) {
console.log(score);
}输出:
80
90
70要访问循环内数组元素的索引,可以使用数组的 entries() 方法与 for...of 语句。 array.entries() 方法在每次迭代中返回索引与元素 [index, element]。
例如:
let colors = ['Red', 'Green', 'Blue'];
for (const [index, color] of colors.entries()) {
console.log(`${color} is at index ${index}`);
}输出:
Red is at index 0
Green is at index 1
Blue is at index 2在此示例中,我们使用数组解构将 entries() 方法的结果分配给每次迭代中的 index 和 color 变量:
const [index, color] of colors.entries()for…of 循环对象解构
考虑以下示例:
const ratings = [
{user: 'John',score: 3},
{user: 'Jane',score: 4},
{user: 'David',score: 5},
{user: 'Peter',score: 2},
];
let sum = 0;
for (const {score} of ratings) {
sum += score;
}
console.log(`Total scores: ${sum}`); // 14输出:
Total scores: 14如何运行:
ratings是一个对象数组。每个对象都有两个属性 user 和 score。for...of遍历ratings数组并计算所有对象的总分。- 表达式
const {score} of ratings使用对象解构将当前迭代元素的score属性分配给score变量。
遍历字符串
以下示例使用 for...of 循环迭代字符串的字符。
let str = 'abc';
for (let c of str) {
console.log(c);
}输出:
a
b
c遍历 Map 对象
下面的示例说明如何使用 for...of 语句迭代 Map 对象。
let colors = new Map();
colors.set('red', '#ff0000');
colors.set('green', '#00ff00');
colors.set('blue', '#0000ff');
for (let color of colors) {
console.log(color);
}输出:
[ 'red', '#ff0000' ]
[ 'green', '#00ff00' ]
[ 'blue', '#0000ff' ]
Code language: JSON / JSON with Comments (json)
遍历集合对象
下面的例子展示如何使用 for...of 循环遍历一个 set 对象:
let nums = new Set([1, 2, 3]);
for (let num of nums) {
console.log(num);
}for...of 与 for...in 对比
for...in 遍历对象的所有可枚举属性。它不会遍历诸如 Array,Map 或 Set 之类的对象。
与 for...in 循环不同,for...of 循环迭代一个集合,而不是一个对象。事实上,for...of 迭代遍历具有 [Symbol.iterator] 属性的集合。
下面的例子说明 for...of 和 for...in 之间的区别。
let scores = [10,20,30];
scores.message = 'Hi';
console.log("for...in:");
for (let score in scores) {
console.log(score);
}
console.log('for...of:');
for (let score of scores) {
console.log(score);
}
输出:
for...in:
0
1
2
message
for...of:
10
20
30在此示例中,for...in 语句遍历 scores 数组的属性:
for...in:
0
1
2
message而 for...of 遍历数组的元素:
for...of:
10
20
30结论
使用 for...of 循环迭代可迭代对象的元素。