给定一个数组,数组内每个元素相加。
forEach()是ECMAScript 5定义的一种遍历数组元素的方法,按照索引的顺序按个传递给定义的一个函数。
语法:array.forEach(function(item, index, arr), thisValue)
参数解释:
item: 当前数组元素 (必须要)。
index: 当前元素的索引。
arr: 当前数组。
thisValue: 表示执行回调函数callback()时的this指向,可选参数。当不写时,则默认是指向window全局
案例代码:
<script>
var arry=[1,2,3,5,100];
function sum (arr){
var sum=0;
arr.forEach(function(item){
sum+=item;
});
return sum;
}
console.log(sum(arry));
</script>