简体   繁体   English

如何修复一个简单的js计算器(返回未定义)

[英]How to fix a simple js calculator (returns undefined)

I have this task to create a calculator using only one JS object. 我的任务是仅使用一个JS对象创建一个计算器。 No matter what I do it returns 'undefined' and I can't understand what is wrong. 无论我做什么,它都会返回“ undefined”,并且我无法理解什么地方出了问题。 I understand that it has something to do with default values, but not stating 'undefined' deliberately has also return an error. 我知道这与默认值有关,但没有故意声明“未定义”也会返回错误。 All the methods should work fine, but somehow they just don't. 所有方法都可以正常工作,但是某种程度上却行不通。

 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()); 

You never return any value from the calculation() function. 您永远不会从calculation()函数返回任何值。 You need to return the value of the function result inside your switch() : 您需要在switch()内部返回函数结果的值:

switch(mathSign) {
    case '+': 
        return this.addition();
    case '-':
        return this.subtraction();
    case '*': 
        return this.multiplication();
    case '/':
        return this.division();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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