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
  • 50,196
  • 9
  • 100
  • 118
Vincent
  • 65
  • 6

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
  • 50,196
  • 9
  • 100
  • 118
Jed
  • 10,649
  • 19
  • 81
  • 125
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,962
  • 12
  • 20
0

The reason is because:

for (tick in ticker) {
  console.log(tick) //tick equal 0
}
Grant Miller
  • 27,532
  • 16
  • 147
  • 165
Big Yang
  • 46
  • 4