行业知识
for each和for of的区别
2026-11-14 09:03:34
来源:互联网转载
- forEach���法:
- forEach是Array对象的方法,可以直接使用。
- forEach会对数组中的每个元素执行指定的回调函数,但无法在回调函数中使用break或return来中止循环。
- 回调函数接受三个参数:当前遍历的元素值、当前遍历的索引和整个数组本身。
- forEach不返回任何值,它只是用于遍历数组并执行操作。
const arr = [1, 2, 3, 4];arr.forEach((element, index) => { console.log(`Element at index ${index}: ${element}`);});//输出结果Element at index 0: 1Element at index 1: 2Element at index 2: 3Element 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: 1Element: 2Element: 3Element: 4 - forEach适用于需要对每个数组元素执行相同操作的情况,而且不需要中止循环。
- for...of适用于需要在遍历过程中使用break或return来中止循环的情况,或者需要直接访问当前元素的值。此外,for...of也适用于遍历其他可迭代对象,如字符串、Set和Map等。 ()()
上一篇:单机传奇服务器怎么转公网?
下一篇:vue 前端预览 Excel 表