建立一个函数,根据平均值和投票数返回1-5的投票数

时间:2020-06-30 21:36:17

标签: javascript math

嘿,比我聪明的人,

我目前正在开发一个函数,该函数以给定的平均评分(1-5)和许多评论(任何)。我试图找出处理此问题的最佳方法,因为我无法获得每张选票,我试图以仍能满足平均水平的方式来建立选票。这就是我开发的内容,但是,我目前遇到一个错误,即所有选票均投给了平均值,即使我专门针对每个选票的目标数乘以一个小数,并使用math.round来转义小数。

你们都怎么想?有没有更好的方法可以探索这一点?

let avg = Math.floor((Math.random()*5)+1);
console.log('Current Avg is',avg);
let numberOfVotes = Math.round(Math.random()*50)
console.log('Current Number of Votes is',numberOfVotes);

function buildSomeFakeNums (avg,numberofvotes){
  avg = Math.round(avg);
let votes = {
  1:0,
  2:0,
  3:0,
  4:0,
  5:0,
}

// -------------- Handling Averages ----------
  //1 or 5
  if (avg === 1 || 5){
    votes[avg] = numberofvotes;
    return votes;
  }
  //2
  if (avg === 2){
    votes[1] = Math.round(numberofvotes * .20);
    votes[avg] = Math.round(numberofvotes * .60);
    votes[3] = Math.round(numberofvotes * .15);
    votes[4] = Math.round(numberofvotes * .05);
  }
  //3
  if (avg === 3){
    votes[1] = Math.round(numberofvotes * .05);
    votes[2] = Math.round(numberofvotes * .15);
    votes[avg] = Math.round(numberofvotes *.60);
    votes[4] = Math.round(numberofvotes * .15);
    votes[5] = Math.round(numberofvotes * .05);
  }
  //4
  if (avg === 4){
    votes[2] = Math.round(numberofvotes * .05);
    votes[3] = Math.round(numberofvotes * .15);
    votes[avg] = Math.round(numberofvotes *.60);
    votes[5] =Math.round( numberofvotes * .20);
  }
  console.log(votes)
  return votes;
}

buildSomeFakeNums(avg,numberOfVotes);

1 个答案:

答案 0 :(得分:0)

问题出在以下这一行:if (avg === 1 || 5){,因为它将始终为true(认为5为true)。

if (avg === 1 || avg === 5){替换它,它应该可以工作。

相关问题