Purixi Purixi - 1 year ago 70
Javascript Question

What am I doing wrong with arrays?

I'm pretty new to the JavaScript as well as to the Node.JS and I really can't understand why I'm getting NaN using the following expression:

var aUsersBetted = {};
aUsersBetted['1337'] += 200000;

After doing this it prints me NaN in console. I'm really confused now. Sorry for the dumb question by the way.

Answer Source

Let's take it line by line.

This var aUsersBetted = {}; creates an object, not an array.

This aUsersBetted['1337'] += 200000; adds 200000 to the value that is associated with the key 1337.

Since, you haven't defined the key before you use it, it's value is also undefined. So you try to add to an undefined value to a number. That's why you get this error.

One possible workaround to your problem it would be to initialize the value of 1337, like:

aUsersBetted['1337'] = 0;

Then your expression, aUsersBetted['1337'] += 200000;, would add 200000 to 0 and set this to the back to the place in memory, where aUsersBetted['1337'] points to.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download