我正在为像函数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);
};
发布于 2016-10-05 17:39:36
问题在于您如何使用pop。pop从数组中移除最后一项并返回最后一项。您应该像这样重写您的函数:
RPNCalculator.prototype.minus = function() {
let lastName = this.pop();
let firstNum = this.pop();
this.push(firstNum - lastNum);
};https://stackoverflow.com/questions/39862073
复制相似问题