减号操作始终返回正值

时间:2016-10-04 21:29:59

标签: javascript rpn

我正在为函数RPNCalculator创建一个数组的方法,但由于某种原因它无法正常工作。

例如,当我尝试执行操作3 - 8时,它将返回5而不是-5,对于3 - 4,它将返回1而不是-1。你可以在 num 变量中看到它。

我真的很感谢你的帮助。

RPN是[2,3,4]

RPNCalculator.prototype.minus = function() {
	console.log("First item " + this[this.length - 2] + "\nLast Item " + this[this.length - 1]); 
        /* Logs:First item 3
                Last Item 4 */
	var num = this.pop(this[this.length - 2]) - this.pop(this[this.length - 1]);
	console.log(num);    // logs 1
	this.push(num);
};

1 个答案:

答案 0 :(得分:0)

问题在于您如何使用poppop从数组中删除最后一项并返回最后一项。你应该像这样重写你的函数:

RPNCalculator.prototype.minus = function() {
  let lastName = this.pop();
  let firstNum = this.pop();
  this.push(firstNum - lastNum);
};
相关问题