计算排除的平均值-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