计算排除平均值 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming
假设我们有一个像这样的对象数组 −
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 标志设置为布尔值的对象的 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