【ES6 教程】第一章 新的ES6语法08— for…of 循环

ES6教程1年前 (2023)发布 admin
1,193 0

在今天的教程中,我们将学习如何使用 JavaScript for…of 语句来迭代可迭代对象。

JavaScript for…of 循环简介

ES6 引入了一个新的 for…of 语句,它遍历一个可迭代的对象,例如:

  • 内置Array , String , Map , Set , …
  • 类似数组的对象,例如参数或 NodeList
  • 实现迭代器协议的用户定义对象。

下面说明了 for…of 的语法:

for (variable of iterable) {
// …

variable

在每次迭代中,将可迭代对象的属性分配给variable。 我们可以使用 var、let 或 const 来声明变量。

iterable

可迭代对象是其可迭代属性被迭代的对象。

JavaScript for of 循环示例

让我们看一些使用 for…of 循环的例子。

1) 遍历数组

下面的例子展示了如何使用 for…of 来遍历数组的元素:

let scores = [80, 90, 70];

for (let score of scores) {
score = score + 5;
console.log(score);

输出:

85
95
75

在此示例中,for…of 迭代了 score 数组的每个元素。它在每次迭代中将scores数组的元素分配给变量score。

如果我们不改变循环内的变量,我们应该使用 const 关键字而不是 let 关键字,如下所示:

let scores = [80, 90, 70];

for (const score of scores) {
console.log(score);
}

输出:

80
90
70

要访问循环内数组元素的索引,可以使用 for…of 语句和数组的 entries() 方法。

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

在此示例中,我们使用数组解构将 entry() 方法的结果分配给每次迭代中的 index 和 color 变量:

const [index, color] of colors.entries()

2) 使用 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} 使用对象解构,将当前迭代元素的 score 属性分配给 score 变量。

3) 遍历字符串

以下示例使用 for…of 循环遍历字符串的字符。

let str = ‘abc’;
for (let c of str) {
console.log(c);
}

输出:

a
b
c

4) 迭代 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’ ]

5) 迭代set对象

下面的例子展示了如何使用 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…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 循环遍历可迭代对象的元素。

 

英文 | https://www.javascripttutorial.net
翻译 | 杨小爱

© 版权声明

相关文章

暂无评论

暂无评论...