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

52df0108230aedd4e32f74ec2053ad74.png

英文 | https://www.javascripttutorial.net

翻译 | 杨小爱

在今天的教程中,我们将学习如何使用 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 循环遍历可迭代对象的元素。

推荐阅读

【ES6 教程】第一章 新的ES6语法01—let:使用let关键字声明块范围的变量

【ES6 教程】第一章 新的ES6语法02—var 和 let 的区别

【ES6 教程】第一章 新的ES6语法03—使用const 关键字定义常量

【ES6 教程】第一章 新的ES6语法04—如何设置函数参数的默认值

【ES6 教程】第一章 新的ES6语法05—REST 参数以及如何有效地使用它们

【ES6 教程】第一章 新的ES6语法06—JavaScript 扩展运算符

【ES6 教程】第一章 新的ES6语法07—ES6 提供了一种定义对象字面量的新方法

学习更多技能

请点击下方公众号

c667add721dcf1bf77019752f442c59e.gif

84bf5bed09e7ec95d1dd80c3f26b7d34.png

f5039aad2044d4ab0a644452ac1439ea.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值