查找数组中有多少项大于或小于给定数字 Javascript

 let numbers = [2, 2, 6, 10];




const findAvarage = (numbers) => {

  let total = 0;

  let checkIntegers = numbers.every(i => !Number.isInteger(i))


  if (checkIntegers = true) {

    for(let i = 0; i < numbers.length; i++) {

    total += numbers[i];

  }

  let avg = total / numbers.length;


   return avg

  } else {

    return "Only integers allowed"

  }

 

 const compareNumbers = (numbers) => {

   

 }

在此代码中,我计算数组中给定数字的平均值,现在我想使用第二个函数查找数组中有多少数字大于平均数


我尝试使用 find 方法,但没有成功,请问有什么解决方案吗?


婷婷同学_
浏览 170回答 5
5回答

湖上湖

您可以使用filter函数过滤掉大于平均值的数字。const&nbsp;avg&nbsp;=&nbsp;findAvarage(numbers) const&nbsp;count&nbsp;=&nbsp;numbers.filter(number&nbsp;=>&nbsp;number&nbsp;>&nbsp;avg).length

德玛西亚99

Javascript 没有提供很多可用于数组的扩展方法,您只有一些基本操作。如果您将此需求转化为数组的扩展,您可以在任何地方使用它们而无需调用函数,您的代码会更干净,您可以执行以下操作:Object.defineProperties(Array.prototype, {&nbsp; &nbsp; count: {&nbsp; &nbsp; &nbsp; &nbsp; value: function(value) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(isNan(value)) return NaN;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return this.filter(x => x>=value).length;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; },&nbsp; &nbsp; average:{&nbsp; &nbsp; &nbsp; &nbsp; value:function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let total = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(!this.every(i => Number.isInteger(i)))&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return NaN;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(let i = 0; i < numbers.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;total += numbers[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return total/this.length;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }});你可以像这样使用它作为你的例子var result = numbers.count(numbers.average())

波斯汪

&nbsp;const compareNumbers = (numbers) => {&nbsp; &nbsp;const avg = findAvarage(numbers);&nbsp; &nbsp;let greater = 0;&nbsp; &nbsp;&nbsp; &nbsp;numbers.forEach((num) => { if (num > avg) greater++; });&nbsp; &nbsp;return greater;&nbsp;}

www说

这边走 ?const findAvarage=(a,b,c,d) => [a,b,c,d].reduceRight((t,n,i,a)=>&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; t += n&nbsp; &nbsp; &nbsp; &nbsp; if (!i) t /= a.length&nbsp; &nbsp; &nbsp; &nbsp; return t&nbsp; &nbsp; &nbsp; &nbsp; },0)&nbsp; ,&nbsp; &nbsp;greaterOrEqualCount = (a,b,c,d) =>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; let avg = findAvarage(a,b,c,d)&nbsp; &nbsp; &nbsp; &nbsp; return [a,b,c,d].reduce((r,n)=>r+(n<avg?0:1),0)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp;&nbsp;console.log("count ",greaterOrEqualCount(2,2,6,10))

翻过高山走不出你

你可以使用filter或reduce来解决它let numbers = [2, 2, 6, 10];function countNumbers(number){&nbsp; return numbers.filter(num=> num>=number).length;}function countNumbers2(number){&nbsp; return numbers.reduce((count,item)=>count+(item>=number),0)}console.log(countNumbers(7));console.log(countNumbers2(3))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript