2016-10-04 2 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 num = 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

あなたがpopを使用しているどのような問題があります。 popは配列から最後の項目を削除し、最後の項目を返します。

RPNCalculator.prototype.minus = function() { 
    let lastName = this.pop(); 
    let firstNum = this.pop(); 
    this.push(firstNum - lastNum); 
}; 
関連する問題