在javascript中解决百分比函数问题

时间:2018-05-16 16:21:34

标签: javascript function

https://jsfiddle.net/kelliwilli/6bgrt7bL/128/

var percent = function() {
  var totalGames = (scores.draw + scores.p1 + scores.Ali);
  var drawPercent = ((scores.draw / totalGames) * 100);
  var AliPercent = ((scores.Ali / totalGames) * 100);
  var p1Percent = ((scores.p1 / totalGames) * 100;

  alert ("There has been " + drawPercent + "% of draws. I won " +     AliPercent + "%, and" +p1 +" won" + p1Percent "%!");
}

2 个答案:

答案 0 :(得分:0)

似乎只是一个简单的语法错误,这不是我认为你遇到的问题或缺乏...

无论如何alert ("There has been " + drawPercent + "% of draws. I won " + AliPercent + "%, and" +p1 +" won" + p1Percent + "%!");应该修复它。你只是忘了连接最后一个变量。

查看模板文字,它们非常便于将带有许多变量的字符串放在一起,以及我发现它们是非常棒的语法。

模板文字形式:

alert(`There has been ${drawPercent}% of draws. I won ${AliPercent}%, and ${p1} won ${p1Percent}%!}); 

答案 1 :(得分:0)

https://jsfiddle.net/kelliwilli/6bgrt7bL/224/

//percent funtion
  var percent = function() {
    var totalGames = (scores.draw + scores.p1 + scores.Ali);
    var drawPercent = ((scores.draw / totalGames) * 100);
    var AliPercent = ((scores.Ali / totalGames) * 100);
    var p1Percent = ((scores.p1 / totalGames) * 100);
    alert("There has been " + drawPercent + "% of draws. Ali won " + AliPercent + "%, and " + p1 + " won " + p1Percent + "% of the games! Thanks for playing!!!");
  }

有些代码不按顺序排列,在定义之前调用函数,而“if”循环应该是“while”。 简单的修复。 :)

这个小提琴链接有效!