Home > Software design >  Adding to i in for loop gives undefined
Adding to i in for loop gives undefined

Time:11-03

Morning all,

I've got a for loop and my aim to to add 2 items together, heres a look at the code:

for(i = 0; i < Orders.length; i  ){
        if(Orders[i].type === 'BUY'){
            pNL.push({total: Orders[i].Qty   Orders[i 1].Qty});
        }
    }

I've seen on this site similar questions that state [i 1] should work however I keep getting an error saying cannot read property Qty of undefined, pointing at Orders[i 1].Qty.

Any help would be appreciated.

CodePudding user response:

Orders[i 1] will be undefined on the very last step of your loop.

CodePudding user response:

Here is your solution

for (let i = 0; i < Orders.length; i  ) {
  if (Orders[i].type === 'BUY') {
    pNL.push({ total: Orders[i].Qty  = Orders[i].Qty});
  }
}

CodePudding user response:

Solved, the issue. I had the above for loop nested inside another both using i to increment, once I separated them it worked as expected.

Obviously this couldnt have been answered by the community since I didnt include it, let this be a lesson to take a step back, the issue is sometimes staring you right in the face. :)

  • Related