![](/img/trans.png)
[英]TypeError: Cannot read property 'split' of undefined (Node js simple calculator)
[英]How to fix a simple js calculator (returns undefined)
我的任務是僅使用一個JS對象創建一個計算器。 無論我做什么,它都會返回“ undefined”,並且我無法理解什么地方出了問題。 我知道這與默認值有關,但沒有故意聲明“未定義”也會返回錯誤。 所有方法都可以正常工作,但是某種程度上卻行不通。
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());
您永遠不會從calculation()
函數返回任何值。 您需要在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.