dimanche 20 janvier 2019

Generate buttons with random numbers in JavaScript and insert into DOM

Hey guys I'm trying to do one project and I got one problem. I generated 2 random numbers and operator - then I got the result for this equation and stored it in an array. I wanted to add other 3 randomly generated numbers to the array (all of the numbers will be displayed on buttons and user will be able to click on one and find out if its the right result). It works only for the first number in the arry, which is the right result. I didnt mange to push the other 3 numbers. Do you know how to do it? Thank you in advance!

window.addEventListener('load', function () {

    var rnum1 = generateRandomNumber1();
    var rnum2 = generateRandomNumber2();
    //pass the random numbers to the function   
    var data = generateRandomOperatorAndCorrectResult(rnum1, rnum2);
    //data=["+", [5]]
    var operator = data[0];
    var allResults = data[results];
    var mes = alert(allResults);


    document.querySelector("#text").textContent = "Kolik je " + rnum1 + operator + rnum2 + "?";
});

function generateRandomOperatorAndCorrectResult(num1, num2) {
    var operators = [{
        sign: "+",
        method: function (rnum1, rnum2) { return rnum1 + rnum2; }
    },
    {
        sign: "*",
        method: function (rnum1, rnum2) { return rnum1 * rnum2; }
    },
    {
        sign: "-",
        method: function (rnum1, rnum2) { return rnum1 - rnum2; }
    }];
    var results = [];

    var selectedOperator = Math.floor(Math.random() * operators.length);
    var randomOperator = operators[selectedOperator].sign;
    var correctResult = (operators[selectedOperator].method(num1, num2)); //pass the numbers to the methods
    results.push(correctResult);
    var randomResult = generateRandomResults(3);
    results.push(randomResult);
    //return multiple values
    return [randomOperator, [results]];
}


function generateRandomResults(nums) {
    for (var i = 0; i < nums; i++) {
        ((Math.floor(Math.random() * 400) + 1))
    }
}




Aucun commentaire:

Enregistrer un commentaire