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
  1. for...of循环:
  2. for...of是ES6引入的语法,用于遍历具有迭代器的可迭代对象(如数组、字符串、set  , map等)。
  • for...of支持使用breakreturn来中止循环。
  • 在每次迭代中,通过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等。
相关文章
|
20天前
|
索引
for in 和 for of的区别
for in 和 for of的区别
|
7月前
bis和bic区别与实现
bis和bic区别与实现
56 0
|
9月前
#{} 和 ${} 的区别是什么?
#{} 和 ${} 的区别是什么?
36 0
|
算法 IDE Unix
C和C++的区别
C和C++的区别
154 0
|
算法 编译器 Linux
C与C++的区别
C与C++的区别
93 0
<%= %>、<%! %>、<%-- --%>和 <% %>四者的区别
<%= %>、<%! %>、<%-- --%>和 <% %>四者的区别
写出 && 和 & 的区别。
写出 && 和 & 的区别。
71 0
|
JavaScript 前端开发 索引
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的循环方式。
83 0
for...in和for...of的区别
setBackgroundImage 和 setImage的区别
setBackgroundImage 和 setImage的区别
163 0