2016-10-04 85 views
0

我正在爲函數RPNCalculator創建一個數組的方法,但由於某種原因它無法正常工作。減號操作總是返回正值

例如,當我嘗試操作3-8時,它將返回5而不是-5,對於3 - 4,它將返回1而不是-1。正如你可以看到它裏面的num變量。

我真的很感謝你的幫助。

RPN爲[2,3,4]

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

+2

不知道你的實現細節,但也許你需要做var var = this.pop(this [this.length - 1]) - this.pop(this [this.length - 2]);'? – Mchl

+1

請注意,您正在記錄'this ['],但您正在減去'this.pop(this [...])'的*返回值*。那麼'this.pop()'返回的是什麼?它有什麼作用?爲什麼在那裏?似乎它可能會返回某種東西的「長度」。 –

+5

正常情況下,['pop'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop)刪除數組中的最後一項,返回該值並且不會沒有任何爭論。你的實現是否改變了? –

回答

0

的問題是您如何使用poppop刪除數組中的最後一項並返回最後一項。你應該像這樣重寫你的函數:

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