计算排除后的平均值 - JavaScript
假设我们有一个包含如下对象的数组 -
const arr = [ {val: 56, canUse: true}, {val: 16, canUse: true}, {val: 45, canUse: true}, {val: 76, canUse: false}, {val: 45, canUse: true}, {val: 23, canUse: false}, {val: 23, canUse: false}, {val: 87, canUse: true}, ];
我们需要编写一个 JavaScript 函数,计算对于 canUse 标记已设置为 true 的所有对象的 val 属性的平均值。
示例
以下为代码 -
const arr = [ {val: 56, canUse: true}, {val: 16, canUse: true}, {val: 45, canUse: true}, {val: 76, canUse: false}, {val: 45, canUse: true}, {val: 23, canUse: false}, {val: 23, canUse: false}, {val: 87, canUse: true}, ]; const excludedAverage = arr => { let count = 0, props = 0; for(let i = 0; i < arr.length; i++){ if(!arr[i].canUse){ continue; }; props++; count += arr[i].val; }; return (count) / (!props ? 1 : props); }; console.log(excludedAverage(arr));
输出
这将在控制台中生成以下输出 -
49.8
广告