jQuery -随机选择和

jQuery - choosing sum at random

本文关键字:选择 随机 jQuery      更新时间:2023-09-26

我正在为小学生创建一个"打地鼠"风格的游戏,他们必须点击与给定总和对应的正确数字。

目前程序正在生成这样的加法和。

function createPlusSum(total) {
    console.log(total)
    var int1 = Math.ceil(Math.random() * total);
    var int2 = total - int1;
    $('#target').html(int1 + ' + ' + int2 + ' = ?');
}   

我已经为减法再次做了这个,它有效,但我不知道从这里开始随机化是否产生加法或减法问题。下面是生成减法题的函数。

function createTakeSum(total) {
    console.log(total)
    var int1 = Math.ceil(Math.random() * total);
    var int2 = total + int1;
    $('#target').html(int2 + ' - ' + int1 + ' = ?');
}

我用它来创建加法和

createPlusSum(total);

我要怎么说

createPlusSum(total);

createTakeSum(total);

试试这个:

function createSum() {
            total = Math.ceil(Math.random() * 10);
    if(Math.random() > 0.5)
    {
        createTakeSum(total);
    } else {
        createPlusSum(total)
    }
}

我会再次使用随机数:

var rand = Math.floor(Math.random()*2);
switch (rand) {
 case 0:
  createPlusSum(total);
  break;
 case 1:
  createTakeSum(total);
  break;
}

我并不是建议您应该这样做,我只是提供了另一种完整的答案。如果代码错了,请原谅。我对JS有点生疏了。

{
    0: createPlusSum,
    1: createTakeSum
}[Math.floor(Math.random() * 2)](total);

你可以给数组字段分配函数,并随机调用。

var func = new Array();
func[0] = function createPlusSum(total) {....};
func[1] = function createTakeSum(total) {....};
var rand = Math.floor(Math.random() * func.length);
func[rand](total);

应该可以,另外你可以添加任意多的函数,只要把它们附加到"func"数组

下面是一个脚本,它在给定范围内创建一个随机的"加"或"减"问题,并在console.log中发布正确的答案:

<div id="target"></div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
  var total = {low: 10, high: 30}; // range
  jQuery(document).ready(function() {
    var total = Math.floor(Math.random() * (total.high - total.low) + total.low);
    var int1 = Math.floor(Math.random() * total);
    var int2 = total - int1;
    if (Math.random() > 0.5) { // add
      var question = int1 + ' + ' + int2 + ' = ?';
      var answer = total;
    }
    else { // subtract
      var question = total + ' - ' + int1 + ' = ?';
      var answer = int2;
    }
    $('#target').html(question);
    console.log('Correct answer: ' + answer);
  });
</script>

下面是jsFiddle的工作示例