Random mathematic Problems

I want to take from the array (mathematicSymbols) or + or - or * random but i can’t do that as a result i have this issue[9+,-,*11+,-,*2+,-,*10]

<!DOCTYPE html>
<html lang="en">
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" href="style.css">
<!--<script src="node.js"></script>-->
 <h1 id="logarithm">Learning maths</h1>
 <form action="#" id="myForm">
	<label>What is:</label>
	<input type="text" id="question" name="question"/>
	<label>The answer is:</label>
    <input type="text" id="answer" name="answer"/>
	<label>Correct answer:</label>
	<input type="text" id="total" name="total"/>
	<button type="button" name="button" class="button" onclick="genQuestion()">New Question</button>
	<button type="button" name="button" class="button" onclick="checkAnswer()">Check Answer</button>
var x, y, z, f;
function generateNumbers() {
    function getRandom12() {
        return Math.floor((Math.random() * 12) + 1);
    x = getRandom12();
    y = getRandom12();
    z = getRandom12();
    f = getRandom12();
let mathematicSymbols = ['+', '-', '*'];
let result = mathematicSymbols.slice(0, 4);
document.getElementById('question').innerHTML = result
function genQuestion() {
   let question = document.getElementById('question').value = x + result + y + result + z + result + f;
    document.getElementById('answer').value = '';
    document.getElementById('total').value = '';

function checkAnswer() {
         question === +document.getElementById('answer').value ?
         'Great!' :
         'Not Yet!.'
     document.getElementById('total').value = question;

genQuestion(); // needed for the first time, could be later an event.

It is because result is an array.

Consider this:

const arr = ['a', 'b', 'c']
const num = 127

console.log(num + arr)
// 127a,b,c

JS sees that it has to deal with a number and an array. I assume that it first runs the toString method on the array so that it can reduce it to something that can combine with a number, ultimately converting that to a string too.

Actually, that was easy to confirm by just overwriting that method:

const arr = ['a', 'b', 'c']
const num = 127
arr.toString = () => ' howdy'
console.log(num + arr)
// 127 howdy
1 Like

And looking at the docs it looks like it just calls join by default.

let result = mathematicSymbols.slice(0, 4);

What are you expecting this to do?

1 Like

I thought if i use this it will make it like a random selector from the array (0, 4) so it willl have the chance to select one of the them

I fixed that by using const randomElement = mathematicSymbols[Math.floor(Math.random()* mathematicSymbols.length)] but right now all the problems will have or - or + or * .But how can i make it to be like this?5 - 4 + 3 * 15

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.