0

I'm trying to do a simple JS loop where I initialize a variable with a value outside the loop, but for some reason its not working.

Basically, I'd like to have total_money equals to 20 in my example, but it keeps returning money

var total = 0;
var money = 20;
var ticker = ['money'];
for (tick in ticker) {
  total_money = ticker[tick];
}

console.log(total_money);
Dennis Vash
  • 42,190
  • 6
  • 81
  • 99
Vincent
  • 45
  • 5

3 Answers3

0

Remove the single-quotes '...' from your array called ticker:

var total = 0;
var money = 20;
var ticker = [money]; // <-- Remove the single-quotes
for (tick in ticker) {
  total_money = ticker[tick];
}

console.log(total_money);
Dennis Vash
  • 42,190
  • 6
  • 81
  • 99
Jed
  • 10,231
  • 17
  • 79
  • 122
0

I know this is a simplified version of the code, but just be aware that you are not adding up total_money but overwriting

So if you have another ticker. For example:

var total = 0;
var money1 = 20;
var money2 = 30;
var ticker = [money1,money2];
for (tick in ticker) {
  total_money = ticker[tick];
}

console.log(total_money);

You will get total_money = 30, not 50.

You can fix this by doing total_money += ticker[tick]

Also note that you are looping through one item.

Bergur
  • 3,580
  • 10
  • 18
0

The reason is because:

for (tick in ticker) {
  console.log(tick) //tick equal 0
}
Grant Miller
  • 24,187
  • 16
  • 134
  • 150
Big Yang
  • 36
  • 4