Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>reduce</title>
</head>
<body>
  <script>
    /*
    *注:reduce默认有三个参数,第一个参数是每一次求值的结果值(初始等于数组第一项),
    *第二个参数是下一项要计算的项,第三个值为第二个参数在数组中的索引
    */
    var arr = [60,20,31,54];
    //求数组各项和
    var result = arr.reduce(function(temp,next,index){
      return temp+next;
    });
    //求平均值
    var result0 = arr.reduce(function(temp,next,index){
      if(index < arr.length-1){
        return temp + next;
      }else{
        return (temp+next) / arr.length;
      }
    })
    console.log(arr,result,result0);
  </script>
</body>
</html>
Output 300px

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers