javascript - While operator undefined -
i want make small calculator in javascript. got html code looking (for numbers)
<button type="button" onclick="calcnum(1)">1</button> <button type="button" onclick="operator('+')">+</button> var mynumbers = [];
the calcnumber function this:
function calcnum(i) { mynumbers.push(i); var x = document.getelementbyid("screen").innerhtml = mynumbers.join(""); }
and operator function this:
function operator(op) { var operator = op; var y = document.getelementbyid("screen").innerhtml = operator; }
my goal make this: if press 1,2,3 want screen element display "123" (which does) if press "+" want "+" displayed (which does) when operator pressed, , new number pressed want start on new number, right if press "123" , + , "456" get:
123456, instead want display "456", hence starting on new number. hope it's clear.
i figured add calcnum function:
while(op == "undefined") { keep pushing numbers // not work }
in end want construct calc function takes numbers operator pressed first number, concatanate operator , second number , adding them together.
i see several issues in code don't know if due fact didn't copy code in question.
first, operator
function incorrect : give local variable samename function. if want function return value, use return
keyword.
i figured add calcnum function:
while(op == "undefined") { keep pushing numbers // not work }
where op
defined? op
see local variable of operator
function. undefined
in calcnum
.
note if want test if variable undefined, should not test
if (myvar == "undefined")
but
if(typeof myvar == "undefined")
finally i'd change code way (should tested though):
var currentnumber= ""; var entries = [] function calcnum(i) { currentnumber +=i; document.getelementbyid("screen").innerhtml = currentnumber; } function operator(op) { var y = document.getelementbyid("screen").innerhtml = op; //note process entered operations if clicked on '=' //and display result instead of displaying operation... if(currentnumber != ""){//there must number entered before click on operator entries .push(currentnumber); entries .push(op); currentnumber= ""; } }
and still need of course implement when click on =
...
Comments
Post a Comment