2

This is a problem I have for totalMade variable and the totalEntry variable. The final tally of the variables always doubles (it's always two times the number it's supposed to be). I snooped around and found out that the tally is normal after the first if statement, then it suddenly doubles after finishing the entire for-in loop. Any ideas what the problem might be?

db is an array that contains an object in every cell. There are hundreds of cells/hundreds of objects.

Here's the code for reference:

for (var z in db) {
    if (isNaN(Number(db[z]["Balance ($)"])) && isNaN(Number(db[z]["Made ($)"]))) {
    } else {
        if (db[z].Opponent === "Cancelled") {
        } else {
            totalEntry += Number(db[z]["Entry ($)"]);
            totalMade += Number(db[z]["Made ($)"]);
            cleanArray.push(db[z]);
            dateLists.push(db[z].Date);
            sampleData.push(Number(db[z].Score));

            if (db[z].Type === "alpha") {
                totalAlphaEntries++;
            } else if (db[z].Type === "beta") {
                totalBetaEntries++;
            } else if (db[z].Type === "gamma") {
                totalGammaEnties++;
            } else if (db[z].Type === "theta") {
                totalThetaEntries++;
            }

        }
    }
}
Mabeh Al-Zuq Yadeek
  • 46
  • 4
  • 16
  • 28
  • 1
    Is the `totalMade` variable global and this code being called in an event handler? If you don't reset the totals each time, you might just be running this code more often that expected. – David Oct 23 '15 at 21:16
  • How many times does it run the for loop? You say it's correct after the first iteration. How about the second, the n'th? – arcyqwerty Oct 23 '15 at 21:16
  • db is an array or an object? – GramThanos Oct 23 '15 at 21:18
  • be warned that javascript's for construct may not be doing what you expect: http://stackoverflow.com/a/500531/4206756 – Hypaethral Oct 23 '15 at 21:20
  • do: console.log(db[z]) and see logs in browser and then do checking manually. I think data that comes and what You think that would be are not same. check this also: console.log(Number(db[z]["Entry ($)"])); – num8er Oct 23 '15 at 21:20
  • db is an array of hundreds of objects. – Mabeh Al-Zuq Yadeek Oct 23 '15 at 21:20
  • 1
    if its an array use `db.forEach()` or the traditional `for(var i = 0; i < db.lengthl i++)`. `for in` is meant for iterating object properties. – ste2425 Oct 23 '15 at 21:22
  • it is an array, but in each cell, there is an object that is iterated through to get the specific data that I need. – Mabeh Al-Zuq Yadeek Oct 23 '15 at 21:25
  • You're not iterating the object, you're retrieving property values. You should, however, iterate the array properly, as mentioned. – James Oct 23 '15 at 21:26
  • alright, thanks for the suggestions. I'll re-write the logic and use your suggestions. – Mabeh Al-Zuq Yadeek Oct 23 '15 at 21:38

0 Answers0