我的任务是仅使用一个 JS 对象创建一个计算器。无论我做什么,它都会返回“未定义”,我无法理解出了什么问题。我知道它与默认值有关,但不故意声明“未定义”也会返回错误。所有的方法都应该可以正常工作,但不知何故他们就是不行。
var Calculator = {
x: undefined,
y: undefined,
addition: function() {
var result = this.x + this.y;
return result;
},
division: function() {
var result = this.x / this.y;
return result;
},
multiplication: function() {
var result = this.x * this.y;
return result;
},
subtraction: function() {
var result = this.x - this.y;
return result;
},
calulation: function() {
var mathSign;
this.x = +prompt('Please insert a first number: ');
this.y = +prompt('Please enter a second number: ');
if (isNaN(this.x) || isNaN(this.y)) {
alert('Please insert a number!');
this.x = +prompt('Please insert a first number: ');
this.y = +prompt('Please enter a second number: ');
}
mathSign = prompt('Please enter a math symbol: (+, -, *, /)');
if (mathSign == '+' || mathSign == '-' || mathSign == '*' || mathSign == '/') {
switch (mathSign) {
case '+':
this.addition();
case '-':
this.subtraction();
case '*':
this.multiplication();
case '/':
this.division();
}
} else {
alert('An input should be a math symbol! (+, -, *, /)')
}
}
}
console.log(Calculator.calulation());Run Code Online (Sandbox Code Playgroud)
你永远不会从calculation()函数中返回任何值。您需要在您的内部返回函数结果的值switch():
switch(mathSign) {
case '+':
return this.addition();
case '-':
return this.subtraction();
case '*':
return this.multiplication();
case '/':
return this.division();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
229 次 |
| 最近记录: |