-2

So I'm using a constructor like this

const RPNCalculator = function () {
  let methods = {
  numberList: [],
  calc: 0,   
  push(num) {
   this.numberList.push(num);
  },
  plus() {
    for (let i = 0; i <= this.numberList.length; i++) {
      console.log('before:' + this.calc);
      this.calc = this.calc + this.numberList[i];
    }
    console.log('after:' + this.calc);
    this.numberList = [];  
  }
};
  return methods;
}

const rpnCalculatorInstance = new RPNCalculator; 

The fist console.log prints correctly and adds the elements but the second console.log prints NaN. I've used this pattern before with Object.create but for some reason the this.calc variable isn't persisting when using a constructor. Any help is appreciated!

  • 3
    Probably you need to change this `i <= this.numberList.length` to this `i < this.numberList.length` – Ele Oct 04 '18 at 00:51
  • Possible dupe [Loop through an array in JavaScript](https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript) – Ele Oct 04 '18 at 00:56

2 Answers2

0

you can use reduce to sum up an array https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

run snippet below

class RpnCalculator{
 constructor(){
  this.numberList = [];
  this.push = (num) => { this.numberList = [...this.numberList, num ]}
  this.sum = () => {return this.numberList.reduce(( a, c) => a + c, 0);}
  }
}

const rpnCalculator = new RpnCalculator();
rpnCalculator.push(1)
rpnCalculator.push(2)
rpnCalculator.push(3)
console.log(rpnCalculator.sum());
Bryan Dellinger
  • 4,724
  • 7
  • 33
  • 79
-1

Apparently with the dataset I was given the last item in the array was an undefined element. I fixed it by using

    if (typeof (this.numberList[i]) === 'number') {
      console.log('before:' + this.calc);
      this.calc = this.calc + this.numberList[i];
    }
  • 1
    You need to understand how to loop over an array and understand zero-base indexes. – Ele Oct 04 '18 at 00:55
  • Yes I realized this an exercise or 2 after. Basically the array was 5 long and I was trying to loop over it 6 times. – Bryan Stevens Oct 04 '18 at 01:48