一、forEach的概念: forEach循环是:数组对象的一个内置方法,用于遍历数组的每个元素并执行指定的回调函数
二、基本语法:
数组名.forEach(function (item, index,array) {
})
该回调函数接受三个参数:当前元素的值itemt、当前元素的索引index和正在遍历的数组array。
三、 一些基本例子能更好的理解 假设我们有一个数字数组,并且想要打印出所有偶数:
const numbers = [1, 2, 3, 4, 5, 6];
numbers.forEach(function(number) {
if (number % 2 === 0) {
console.log(`偶数: ${number}`);
}
});
简单遍历并打印元素
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(value) {
console.log(value);
});
// 输出:
// 1
// 2
// 3
// 4
// 5
基于索引的条件操作
const fruits = ['苹果', '香蕉', '橙子', '葡萄'];
fruits.forEach((fruit, index) => {
if (index === 0) {
console.log('第一个水果是: ' + fruit);
} else if (index === fruits.length - 1) {
console.log('最后一个水果是: ' + fruit);
} else {
console.log('其他的水果之一: ' + fruit);
}
});
当forEach面对空的数组的时候,打印出的会是什么?
const arr = [ ];
arr.forEach(function (item) {
console.log('这个消息不会打印出来,因为数组是空的');
});
这里不会进入循环 因为它是一个空的数组
for循环和forEach的区别
①:中断循环不同 for循环是可以中断循环(利用break语句或continue语句) forEach是没有 ②:写法不同(众所周知) for(let i = 0; i<数组的长度;i++){
}
数组名.forEach(function (数组中的元素, 数组中元素的下标) {
}) ③:实现原理不同 for循环:通过下标,对循环中的代码反复执行,功能强大,可以通过index取得元素。在处理比较复杂的处理的时候较为方便。
foreach:从头到尾,对于集合中的对象遍历。适用于简单的遍历。foreach使用的时候,会锁定集合的对象,期间不能进行新增/修改