比较Javascript中的两个随机数

时间:2017-07-22 20:27:10

标签: javascript random numbers compare

我是Javascript的新手,并且在过去的几个小时里一直试图找到答案。无论是9还是9。 1或1> 9,打印到我的HTML的是'true'...而对于第二个声明,它应该是假的......

如果有人能指出我正确的方向,我会很感激!

var ran1 = parseInt( Math.floor(Math.random() * 10) + 1)
var ran2 = parseInt( Math.floor(Math.random() * 10) + 1)
var ctx = document.getElementById('game').getContext('2d');
ctx.font="2em Verdana";
ctx.fillText(ran1,350,50);
ctx.fillText(ran2,450,50);

document.onkeydown = function (e) {

if (e.keyCode == 39) {

  (ran1 > ran2)
    if (true) {
   ctx.fillText('true', 100, 100);
 } else if (false)
   ctx.fillText('false', 100, 200);
 }

if (e.keyCode == 37) {

 (ran2 > ran1)
 if (true) {
  ctx.fillText('true', 100, 100);
} else if (false)
    ctx.fillText('false', 100, 200);
  }}

2 个答案:

答案 0 :(得分:1)

您需要做的是实际测试您正在寻找的条件。例如:

if (ran1 > ran2) {
   ctx.fillText('true', 100, 100);
 } else if (false)
   ctx.fillText('false', 100, 200);
 }

您正在测试if(true),这始终是真的。因为真的总是如此。 ;)

答案 1 :(得分:0)

if (true) {将始终返回true,因为该语句正在将truetrue进行比较(始终为true)。

您需要的是比较您关心比较的实际数字。

var ran1 = parseInt( Math.floor(Math.random() * 10) + 1)
var ran2 = parseInt( Math.floor(Math.random() * 10) + 1)
var ctx = document.getElementById('game').getContext('2d');
ctx.font="2em Verdana";
ctx.fillText(ran1,350,50);
ctx.fillText(ran2,450,50);

document.onkeydown = function (e) {

// Is it true that e.keyCode equals 39?
if (e.keyCode == 39) {

  // Is it true that ran1 is greater than ran2?
  if (ran1 > ran2) {
    ctx.fillText('true', 100, 100);
  } else if (false)
    ctx.fillText('false', 100, 200);
  }

  // Is is true that e.keyCode equals 37?
  if (e.keyCode == 37) {

    // Is it true that ran2 is greater than ran1?
    if (ran2 > ran1) {
      ctx.fillText('true', 100, 100);
    } else if (false)
      ctx.fillText('false', 100, 200);
    }
  }