for each和for of的区别

简介: for each和for of的区别

forEach方法:

       forEach是Array对象的方法,可以直接使用。

forEach会对数组中的每个元素执行指定的回调函数,但无法在回调函数中使用break或return来中止循环。


回调函数接受三个参数:当前遍历的元素值、当前遍历的索引和整个数组本身。

       forEach不返回任何值,它只是用于遍历数组并执行操作。

 
let arr = [1, 2, 3, 4];
 
arr.forEach((element, index) => {
  console.log(`Element at index ${index}: ${element}`);
});
 
//输出结果
Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Element at index 3: 4

for...of循环:

for...of是ES6引入的语法,用于遍历具有迭代器的可迭代对象(如数组、字符串、set  , map等)。

for...of支持使用break和return来中止循环。

在每次迭代中,通过of关键字将当前元素的值赋给一个变量,可以直接访问该值

 

 
const arr = [1, 2, 3, 4];
 
for (const element of arr) {
  console.log(`Element: ${element}`);
}
//输出结果
Element: 1
Element: 2
Element: 3
Element: 4
  • forEach适用于需要对每个数组元素执行相同操作的情况,而且不需要中止循环。
  • for...of适用于需要在遍历过程中使用breakreturn来中止循环的情况,或者需要直接访问当前元素的值。此外,for...of也适用于遍历其他可迭代对象,如字符串、Set和Map等






目录
打赏
0
0
0
0
4
分享
相关文章
|
10月前
|
bindtap和catchtap的区别?
bindtap和catchtap的区别?
113 0
|
10月前
|
1. 认识C++和C的区别
1. 认识C++和C的区别
135 0
|
6月前
i++和++i的区别
i++和++i的区别
66 3
jupternotebook和jupterLab有什么区别?
jupternotebook和jupterLab有什么区别?
1259 0
bis和bic区别与实现
bis和bic区别与实现
242 0
for...in和for...of的区别
前言 在JavaScript中遍历数组通常是使用for...i循环,在ES5具有遍历数组功能的还有forEach、map、filter、some、every、reduce、reduceRight等。 for...in和for...of是两种增强型循环,for...in是ES5标准,在ES6中新增了for...of的循环方式。
129 0
for...in和for...of的区别
getMeasuredWidth和getWidth的区别
View的getWidth()和getMeasuredWidth()有什么区别吗? View的高宽是由View本身和Parent容器共同决定的。getMeasuredWidth()和getWidth()分别对应于视图绘制的measure和layout阶段。
1557 0
C/S 与 B/S 的区别
1.硬件环境不同:   C/S 一般建立在专用的网络上, 小范围里的网络环境, 局域网之间再通过专门server提供连接和数据交换服务.   B/S 建立在广域网之上的, 不必是专门的网络硬件环境,例与电话上网, 租用设备.
1161 0