[英]Why does my javascript not work when I use an if statement in my function
so I'm a javascript beginner and I'm working on making a calculator. 因此,我是一名JavaScript初学者,正在致力于制作计算器。 Right now I'm just testing out my addition button but I'm having troubles with the code on the equal button. 现在,我只是在测试自己的加法按钮,但是在等按钮上的代码遇到了麻烦。 the code for the button is : 该按钮的代码是:
function equalPress() {
storedNumberTwo = document.getElementById("output").innerHTML;
// if(sign === 1) {
calc = +storedNumberTwo + +storedNumber;
document.getElementById("output").innerHTML = calc;
// }
}
I've commented out the if statement to show what I've done to sort of get it working. 我已经注释掉if语句,以显示我为使它正常工作所做的事情。 When I don't use the if statement I can get the equals sign to add and work properly, however, this is obviously not going to work well when I'm adding in the other operators. 当我不使用if语句时,我可以得到等号来添加并正常工作,但是,当我添加其他运算符时,这显然不能很好地工作。 The sign variable is what I was going to use as a switch for which operator was pressed 1= +, 2 = -, etc... Anyways when I add the if statement in so that I can test to see which operator was pressed the whole calculator freezes up and I can't press any buttons. 我将使用sign变量作为按下了哪个运算符的开关1 = +,2 =-等等...无论如何,当我添加if语句时,我可以测试一下按下哪个运算符整个计算器冻结了,我无法按任何按钮。 I'm not sure why this is happening, I've tried using switch instead of if statements and I've used various types of variables for my condition and it hasn't worked. 我不确定为什么会这样,我尝试使用switch而不是if语句,并且针对条件使用了各种类型的变量,但这种方法无效。 Any help would be appreciated. 任何帮助,将不胜感激。 here is my fiddle. 这是我的小提琴。 https://jsfiddle.net/rk1mu4rb/3/ https://jsfiddle.net/rk1mu4rb/3/
Don't use var
to access variables declared in an outer scope. 不要使用var
访问在外部作用域中声明的变量。 The var
keyword inside a function creates a new variable which is local to that function, hiding any other variables with the same name defined outside. 函数内部的var
关键字创建一个新变量,该变量在该函数本地,从而隐藏了在外部定义的具有相同名称的其他变量。
I've updated your fiddle and removed the var
part from sign = 1
: https://jsfiddle.net/rk1mu4rb/4/ 我已经更新了您的小提琴并从sign = 1
删除了var
部分: https : //jsfiddle.net/rk1mu4rb/4/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.