目录
前 言
对于JavaScript初学者,提到遍历数组,我们可能首先想到的是for循环。其实JavaScript中有很多遍历数组的方法,我们今天来介绍一个新的遍历数组的方法——Array.forEach()
1. forEach()方法
语法:array.forEach(callback(currentvalue,index,arr) ,thisValue)
其中
callback
为数组中每个元素执行的函数,该函数可接受1-3个参数:
currentvalue
参数表示数组的当前元素项,必须的参数
index
参数表示的当前元素下标,可选参数
arr
参数表示当前元素所属的数组,可选参数
thisValue
表示执行回调函数callback()时的this指向。可选参数。当不写时,则默认是指向window全局
示例
var arr = [1, 3, 5, 13, 2];
var res = arr.forEach(function(item,index) {
console.log(`数组第${
index+1}个元素是${
item}`);
})
console.log(res);//forEach的返回值为undefined,
运行结果:
敲黑板——forEach()是没有返回值的!
2.forEach()和for循环区别
例如,我们想要找到某个满足条件的元素时就结束循环。
在for语句中我们可以这样写
var arr = [1, 3, 5, 13, 2];
for (var i = 0; i < arr.length; i++) {
if (arr[i] == 3) {
console.log("找到了3,并结束循环");
break;
}
console.log(arr[i]);
}
for语句执行了2次,在第二次找到了数组中的3,并结束了循环。
运行结果:
那forEach()会怎么样呢?
var arr = [1, 3, 5, 13, 2];
arr.forEach(function(item) {
if (item == 3) {
return console.log('找到了3,但未结束遍历');
}
console.log(item);
})
运行结果:
本想着在找到3之后用return结束遍历,结果仍然输出了3后面的元素。
终止或者跳出forEach()循环,除非抛出异常,所以想执行一个数组是否满足某种条件然后返回某值,可以用一般的for循环实现,或者用Array.every()或者Array.some();
Array.every()用于检测数组所有元素是否全部都符合指定条件
Array.some()用于检测数组中的元素是否有任意一个满足指定条件
var arr1 = [1, 3, , 13, 2];
var arr2 = [1, 3, , 13, 2];
for (var i = 0; i < arr1.length; i++) {
arr1[i] = 2;
}
console.log(arr1);
var newarr = [];
arr2.forEach(function(item, index) {
// item = 2; //修改不了原数组
arr2[index] = 2;
})
console.log(arr2);
运行结果:
我们可以发现,for循环对于数组中的空值进行了修改,而forEach()方法跳过了空值。
但要注意的是,我们用forEach()方法修改数组元素不能使用item直接修改,item相当于从arr2中复制过来的值,并不是真正指向原数组arr2里面的元素。所以我们想要修改原数组的每个元素必须通过拿到它的索引值index去进行修改:arr2[index] = 2;
var arr1 = [1, 3, , 13, 2];
var arr2 = [1, 3, , 13, 2];
for (var i = 0; i < arr1.length; i++) {
if (arr1[i] == 3) {
arr1.push(14);
arr1.push(5);
}
console.log("数组循环了" + (i + 1) + "次");
}
console.log(arr1);
var newarr = [];
arr2.forEach(function(item, index) {
if (arr2[index] == 3) {
arr2.push(14);
arr2.push(5);
}
console.log("数组循环了" + index + "次");
})
console.log(arr2);
运行结果:
我们可以发现for循环时,向数组中添加数据,循环次数也增加了。而forEach()方法却只循环数组arr2的初始长度。