forEach()
作用:
对数组中的每一个元素进行一次函数处理,返回一个新的数组,不会改变原数组。
用于调用数组的每个元素,并将元素传递给回调函数。
注意: forEach() 对于空数组是不会执行回调函数的。
注意:forEach()方法没有返回值,不会改变数组,只是对数组每个元素进行一个函数处理。
语法
array.forEach(function(currentValue,index,arr),thisValue);
参数说明:
第一个参数function(currentValue,index,arr);必填,数组中每个元素需要调用的函数。
函数参数:
currentValue必填,当前元素。
index可选,当前元素的索引值。
arr可选,当前元素所属的数组对象。
第二个参数:thisValue可选,传递给函数的值一般用this值,如果这个参数为空,“undefined”会传递给“this”值。
返回值:undefined。
实例
实例1:把数组中的元素都转化成大写。
var fruites = ["apple", "banana", "pear", "orange"];
fruites.forEach((item, index, arrs) => {
let i = item.toLocaleUpperCase();
console.log(i);
});
//输出结果:
//APPLE
//BANANA
//PEAR
//ORANGE
实例2:求一个数组的和
var sum = [2, 4, 1, 9];
let i=0;
sum.forEach((item) => {
i += item;
});
console.log(i);
//结果为
//16
1063

被折叠的 条评论
为什么被折叠?



