我正在尝试使用JavaScript而不使用eval构建计算器。我试图连接一个变量来存储数字。这是正确的方法吗?此外,当我添加到变量时,它前面带有undefined。
var calculator = {
run: function(clicked){
num1: "";
num2: "";
numCheck: false;
switch(clicked){
case "1":
document.getElementById("dis").innerHTML += clicked;
if(this.numCheck===false){
if(this.num1==="undefined"){
this.num1 = " ";
this.num1 = this.num1+"1";
}else{
this.num1 = this.num1+"1";
}
}else{
calculator.run.num2 += "1";
};
我这样做是否正确?
答案 0 :(得分:0)
一些评论:
声明错误this
声明并且您在:
类/函数内使用=
代替run
时声明的格式错误正确应该是:
var calculator = {
run: function(clicked){
this.num1= "";
this.num2= "";
this.numCheck= false;
案例缺失break
和{
赞:
switch(clicked){
case "1":{
//... your code.
break;
}
在使用属于该类的属性时,在函数内部应使用this
而不是使用var calculator
来访问这些属性:
calculator.run.num2 += "1";
正确应该是
this.run.num2 += "1";
这可以转换为单一的:
this.num1 = " ";
this.num1 = this.num1+"1";
像:
this.num1 = " 1";