用JavaScript中的Reduce方法求平均值

时间:2018-09-02 17:59:52

标签: javascript ecmascript-6

最近我尝试使用JavaScript中的Reduce方法计算平均值,这里可能是代码

var arr = [129, 139, 155, 176];

var result = arr.reduce(function (start, end, index, array){
  var total =start + end;
  var array_length = array.length;
  return total/array_length;
});
console.log(result);

我的结果是57.875,但这是错误的,我的问题在哪里以及如何解决?

9 个答案:

答案 0 :(得分:1)

在代码中称为[root@localhost html]# sealert -l e254cabb-7005-4a3c-8f91-8620c924c5e0 SELinux is preventing /usr/sbin/httpd from write access on the file /var/www/html/ow_includes/config.php. ***** Plugin httpd_write_content (92.2 confidence) suggests *************** If you want to allow httpd to have write access on the config.php file Then you need to change the label on '/var/www/html/ow_includes/config.php' Do # semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/ow_includes/config.php' # restorecon -v '/var/www/html/ow_includes/config.php' ***** Plugin catchall_boolean (7.83 confidence) suggests ****************** If you want to allow httpd to unified Then you must tell SELinux about this by enabling the 'httpd_unified' boolean. Do setsebool -P httpd_unified 1 ***** Plugin catchall (1.41 confidence) suggests ************************** If you believe that httpd should be allowed write access on the config.php file by default. Then you should report this as a bug. You can generate a local policy module to allow this access. Do allow this access for now by executing: # ausearch -c 'httpd' --raw | audit2allow -M my-httpd # semodule -i my-httpd.pp Additional Information: Source Context system_u:system_r:httpd_t:s0 Target Context unconfined_u:object_r:httpd_sys_content_t:s0 Target Objects /var/www/html/ow_includes/config.php [ file ] Source httpd Source Path /usr/sbin/httpd Port <Unknown> Host localhost.localdomain Source RPM Packages Target RPM Packages Policy RPM selinux-policy-3.13.1-192.el7_5.6.noarch Selinux Enabled True Policy Type targeted Enforcing Mode Enforcing Host Name localhost.localdomain Platform Linux localhost.localdomain 3.10.0-862.11.6.el7.x86_64 #1 SMP Tue Aug 14 21:49:04 UTC 2018 x86_64 x86_64 Alert Count 108 First Seen 2018-09-02 16:51:25 +0430 Last Seen 2018-09-02 23:00:19 +0430 Local ID e254cabb-7005-4a3c-8f91-8620c924c5e0 Raw Audit Messages type=AVC msg=audit(1535913019.143:9913): avc: denied { write } for pid=5121 comm="httpd" name="config.php" dev="dm-0" ino=18219610 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:httpd_sys_content_t:s0 tclass=file Hash: httpd,httpd_t,httpd_sys_content_t,file,write 的实际上是从上一次迭代返回的结果。在每个步骤中,都将数组的当前元素(称为start)与上一次迭代(end)返回的内容相加,然后将总和除以数组的长度。这确实不是平均值。

以下是使用化简器计算平均值的方法:

start

答案 1 :(得分:0)

您可以添加所有值,这些值除以长度即可得出平均值。

var array = [129, 139, 155, 176],
    average = array.reduce(function (avg, value, _, { length }) {
        return avg + value / length;
    }, 0);

console.log(average);

或取所有值的总和除以数组的长度。结果是一样的。

var array = [129, 139, 155, 176],
    average = array.reduce(function (sum, value) {
        return sum + value;
    }, 0) / array.length;

console.log(average);

答案 2 :(得分:0)

您已重复减少数组的每个项目。其他答案正在做的事情是,他们没有将数组缩小为平均结果,而是求和然后缩小,而您需要2个步骤才能做到。

优秀的函数式程序员,我们想以一种“ 纯一枪”的方式将输入数据转换为我们真正想要的东西。这应该会留下几乎一点代码味道。

更好的方法是使用reduce函数支持的几个参数。

查看代码,希望对您的回答有所帮助。编码愉快:)

     var arr = [129, 139, 155, 176];
    
    function reducer(acc, value, index, array) {
    
      var calculatedValue = acc + value;
    
      if (index === array.length - 1) {
        return calculatedValue / array.length;
      }
    
      return calculatedValue;
    }
    
    var result = arr.reduce(reducer, 0);
    
    console.log(result);

答案 3 :(得分:0)

由于您特别要求ES6:

let arr = [129, 139, 155, 176]
let avg = arr.reduce((a,b) => a+b) / arr.length

答案 4 :(得分:0)

在这里添加一个 ES6+ 箭头函数答案:

const arr = [22,295,176,440,37,105,10,1100,86,52] // Arr values ex.

const calcAverage = (arr) => {
    return arr.reduce((first, next) => first + next) / arr.length
}

// Or even cleaner w/o return/brackets
const calcAverage = (arr) => arr.reduce((first, next) => first + next) / arr.length

const avg = calcAverage(arr)
// Do whatever with averge

答案 5 :(得分:0)

这是一个不使用数组长度的解决方案,可用于计算数字流的平均值:

const average = (numbersArray) =>
  numbersArray.reduce(
    (result, currentValue) => ({
      average: result.average + (currentValue - result.average) / result.count,
      count: result.count + 1,
    }),
    { average: 0, count: 1 }
  ).average;

console.log(average([1, 2, 3, 4, 5, 6]));

答案 6 :(得分:0)

我们可以在 JS 数组中使用 reduce() 属性。

var arr = [1, 2, 3, 4];

const average = (scores) => scores.reduce((sum, elem) => sum + elem, 0) / scores.length)
console.log(average(arr)) // 10

更多详情请见here

答案 7 :(得分:-1)

以下代码有助于了解发生了什么:

var arr = [129, 139, 155, 176];

var result = arr.reduce(function (start, end, index, array){
  
  var total =start + end;
  var array_length = array.length;
  var running_average = total / array_length;

  console.log(`At index ${index}`);
  console.log(`start:${start} end:${end} total:${total}`);
  console.log(`Running average: ${running_average}`);

  return running_average;
});

console.log(result);

按如下方式更改您的代码以解决问题:

var arr = [129, 139, 155, 176];

result = arr.reduce(function(start, end, index, array){
  
  let total = start + end;
  let array_length = array.length;

  // console.log(`At index ${index}`);
  // console.log(`start:${start} end:${end} total:${total}`);
  
  if(index === array_length - 1){
    return total / array_length;
  }
  else{
    return total;
  }
});

console.log(result);

答案 8 :(得分:-1)

const arr = [129, 139, 155, 176];

const calcAverage = (scores) =>
  scores.reduce(
    (accu, ele, i, arrs) =>
      i + 1 === arrs.length ? (accu + ele) / (i + 1) : accu + ele,
    0
  );
console.log(calcAverage(arr));