简体   繁体   中英

Simple javascript calculator if statement

I'm a newbie in JS but I have tried to create an 'if' statement in my calculator, which creates an alert when the result of a multiplication or an addition, etc. is bigger than 20. The calculator works fine but the 'if' statement doesn't.

JS:

var a,b;
function setValues()
{
    a = Number(document.getElementById("a").value);
    b = Number(document.getElementById("b").value);
}

function sum()
{
    setValues();
    result = a+b;
    alert("the sum is equal to "+result);
}
function rest()
{
    setValues();
    result = a-b;
    alert("the rest is equal to "+result);
}
function mult()
{
    setValues();
    result = a*b;
    alert("the operation is equal to "+result);
}
function div()
{
    setValues();
    result = a/b;
    alert("the operation is equal to "+result);
}

if (result > 20) {
    alert("heyy thats pretty big"); 
}

Your if statement should be inside each operator function like so:

function div()
{
  setValues();
  result = a/b;
  alert("the operation is equal to "+result);
  checkResult(result);
}

function checkResult(result){
  if(result > 20)
    alert("heyy thats pretty big");
}

Ask yourself when that 'if' will be executed. It's not inside any of the functions, so how will it be called? I cannot tell without seeing the whole page, but it looks like it will only be executed at the time the page is loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM