在javascript中创建随机数组 [英] create random arrays in javascript

查看:40
本文介绍了在javascript中创建随机数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张表格,要求用户在数学练习中获得最大成绩,以便进行一些练习:

I have a form that asks the user for maximum result in math drills, in order to build some drills:

<input type="text" id="maxR" placeholder="type maximum result" />
<button id="activate" onclick="makeDrills()">MAKE</button>
<p id="drill"></p>

我想将所有演练选项及其答案转换为数组.

And I want to translate all the drills options with their answers as arrays.

我需要将这句话翻译成Java脚本的帮助:

I need help with translating this sentence into java-script:

在c>级别中,同时添加钻头及其结果的新Q数组".

"While c > level add new array of theQ with the both the drill and it's result".

这是我的尝试:

<script>
  function theQ(quest, ans) {  // drills constructor
    this.question = quest;
    this.answer = ans;
  }

  var a, b, c ; // arguments
  var quests = [new theQ()]; // arrays holder
  var level = document.getElementById("maxR").value; // user input

  function makeDrills() { // button pushed
    var c = a+b; // pattern of each drill
    while (c > level) { // as long result smaller then user input
      var a = Math.floor(Math.random() * 10);  // choose random number
      var b = Math.floor(Math.random() * 10); // choose another random number
      quests.push("a+b", "c");  // add the drill to the arrays holder
    }
    document.getElementById("drill").innerHTML += quests; // print drills
  }
</script>

我阅读了类似的问题,并尝试使用他们的技术,但没有成功.

I read similar questions and try to use their techniques but didn't succeed.

该代码用于教育目的:

a,b,c是a + b = c方程的自变量.我尝试让数学练习生成器让孩子输入最大结果,然后按下按钮,然后所有可能的练习选项都会出现.我需要将所有选项作为数组放置,因为我想将这些选项用作某种测试.

a,b,c are arguments on a+b=c equation. I try to make math drills generator that the kid enter maximum result and push the button and then all possible drills options will appear. I need to put all the options as arrays because I want to use the options as sort of a test.

所以现在我只想了解如何创建这些数组.

So for now I just want to understand how to create those arrays.

推荐答案

有几个问题:

  • 创建 questions 数组时,不应在其中添加一个空问题.只需执行 quests = []

  • When you create the quests array, you should not add one empty question to it. Just do quests = []

在使用 a 和 b 的单独值之前,您正在使用 var c = a + b 计算总和. var c = a + b 不是模式-就像您在注释中所写的-一样;它实际上在那里执行加法.

You are calculating the sum with var c = a+b before you have the separate values of a and b. var c = a+b is not a pattern -- as you write in comments --; it actually performs the addition right there.

level 是一个字符串(因为这始终是输入值),因此当您进行类似 c>的比较时,级别,您正在与一个字符串值进行比较,该字符串值将不会达到预期的结果.

level is a string (because that is what input values always are), so when you do a comparison like c > level, you are comparing with a string value, which will not have the desired outcome.

由于您的总和永远都不能大于18( a b 都小于10),因此,如果输入a最大值大于18.此外,将其用作停止条件似乎不合理.您甚至可能陷入第一个总和已经超过允许的情况,而您最终将毫无疑问.只需询问用户或定义代码中的次数即可定义要产生的问题数量(例如10个问题).

Since your sum can never be greater than 18 (a and b are both smaller than 10), your code will run for ever if you enter a maximum value that is greater than 18. Moreover, it seems not reasonable to use this as a stop-condition. You could even get into a situation where the first sum already is greater than allowed, and you'll end up with no questions at all. Just define how many questions you want to produce, either by asking the user for that, or defining the number of times in the code (for example: 10 questions).

通过查看生成第一个数字后剩余的数量,可以确保总和在限制范围内.如果您的最大值是10,并且生成了6,则让您的第二个数字是0到4之间的随机数.这样一来,您始终可以获得有效的数字.

You can make sure that your sum is within limits by looking how much remains after you have generated the first number. If your maximum is 10, and you generated a 6, then let your second number be a random number between 0 and 4. This way you always get valid numbers.

"a + b" 作为问题不是很有用,因为用户不知道 a 是什么意思.而是使其动态并要求 a +'+'+ b +'=',其呈现方式类似于 6 + 3 = .

"a+b" is not very useful as question, as the user does not know what a means. Instead make it dynamic and ask for a + ' + ' + b + ' = ', which will render like 6 + 3 =.

类似地,"c" 是一个字符串,而不是总和的结果,它应该是 c ,或者为什么不只是 a +b ,因此您不需要 c 变量.

Similarly "c" is a string, and not the result of the sum, it should be c, or why not just a+b, so you don't need the c variable.

quests.push("a + b","c"); 将两个字符串值压入数组,但是您想压入一个问题对象,因此需要使用 quests.push(newtheQ(a +'+'+ b +'=',a + b)).

quests.push("a+b", "c"); is pushing two string values to the array, but you want to push a question object, so you need to use quests.push(new theQ(a + ' + ' + b + ' = ', a+b)).

由于 questions 是对象的数组,因此不应期望将其分配给 innerHTML 属性会提供有用的信息.您应该指定问题的呈现方式.因此,您需要遍历所有问题,然后为每个问题生成所需的HTML.

As quests is an array of objects, you should not expect that assigning that to an innerHTML property will render something useful. You should specify how the questions should be rendered. So you need to iterate over the questions, and then generate the piece of HTML you want for each question.

具有所有这些更正的代码如下.它还具有一个按钮和代码来验证答案的输入.

The code with all these corrections is below. It also has a button and code to verify the input of the answers.

function theQ(quest, ans) {  // drills constructor
    this.question = quest;
    this.answer = ans;
}

var quests = []; // array of questions

function makeDrills() { // button pushed
    var a, b; // We don't need c
    // Read the input only when button is pressed:
    var level = document.getElementById("maxR").value; // user input
    // Empty questions array
    quests = [];
    
    // Let's say we want to produce 10 questions
    while (quests.length < 10) { 
        // choose a random integer below the maximum
        a = Math.floor(Math.random() * level);  
        // choose a random integer such that sum is not greater than maximum
        b = Math.floor(Math.random() * (level-a+1));
        // Question is a dynamicly created string, answer is calculated here
        // You need to call theQ here:
        quests.push(new theQ(a + ' + ' + b + ' = ', a+b));
    }

    var container = document.getElementById("drill");
    // Set the HTML for all questions
    container.innerHTML = quests.map(function (quest, i) {
        // Add the question to the drill section, give the input element an ID 
        // that corresponds to the question number
        return quest.question + '<input placeholder="enter sum" id="answer' + i + '"><br>';
    }).join(''); // join all HTML pieces together into one string
}

function verify() {
    if (quests.length == 0) return; // Nothing to do
    // Count the number of wrong answers. Iterate over answers with reduce:
    var errorCount = quests.reduce(function (count, quest, i) {
        // Add 1 penalty if answer is incorrect
        return count + (quest.answer != document.getElementById('answer' + i).value);
    }, 0); // Atart counting from 0
    if (errorCount == 0) 
        alert('Congratulations! You answered all questions correctly.');
    else
        alert('You have entered ' + errorCount + ' wrong answer(s). Try to correct them.');
}

<input type="text" id="maxR" placeholder="type maximum sum" />
<button id="activate" onclick="makeDrills()">Generate questions</button>
<div id="drill"></div>
<button id="verify" onclick="verify()">Verify</button>

这篇关于在javascript中创建随机数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆