Javascript – Calculate value of element with id like-Collection of common programming errors
You are building the price array based on the ‘i’ loop counter. The 10.50 goes into price[0], The quanty of 1 that goes with it is put in qty[1], then i goes through values 2 and 3 with no changes to the arrays. Then when i=4, price[4] gets 19.20 and then qty[5] gets 2 then next time through.
The resulting arrays look like
price[0] = 10.5, price[4] = 19.20
qty[1] = 1, qty[5] = 2
When you loop through the last time to try and so the math, you are essentially doing this:
// i = 0
total = total + price[0] * qty [0] // price[0] = 10.50, but qty[0] = undefined, so total = Nan
// i = 1
total = total + price[1] * qty [1] // price[1] = undefined, qty[1] 1, so total = Nan
// etc.
Make sense?