比较reduce和foreach的区别
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。对空数组是不会执行回调函数的。其实他的作用还有合并数组,相关细节那就看使用情况。
forEach 是 ES5 中操作数组的一种方法,主要功能是遍历数组,其实说穿了,就是 for 循环的加强版,该语句需要一个回调函数,作为参数。回调函数的形参,依次为,value:遍历的数组内容;index:对应的数组索引,array:数组本身。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var arr =[1,5,9,7,12];
// 此处的reduce用于数组内的总和
let result = arr.reduce(function(tmp,item,index){
return tmp + item;
})
console.log(result);
// foreach用于遍历数组:值和索引
arr.forEach((item,index) => {
console.log(index + ':' +item );
});
</script>
</body>
</html>
第一行为使用reduce打印的结果
第二行为foreach打印的结果其结果分别为索引和值