Assignment a number to an attribute using the +=
operator gives me NaN
in JavaScript.
This code works as expected:
> var result = {};
undefined
> result['value'] = 10;
10
> result['value'] += 10;
20
But here we get NaN
:
> var test = {};
undefined
> test['value'] += 10;
NaN
Why does JavaScript behave like this? How can I get this to work without initializing result['value'] = 0
?
You can't add a number to undefined
in JavaScript. If you don't want to initialize the number, you need to test if it's undefined
before incrementing it:
test['value'] = (typeof test['value']==='undefined') ? 10 : test['value']+10;
This line test['value'] += 10
equals to test['value'] = undefined + 10
, which is NaN
(Not a Number).
This happens because you're trying to add 10
to an undefined
property of your object, so your line will result in doing:
test['value'] = undefined + 10; // NaN
Every numerical expression which causes an unknown value turns into NaN
(not a number) in JavaScript. To make it work, you should check if that property exists and has a numerical value, then add some number to it; otherwise you'll have to create it. Plus, since that you're working with an object, you can use test.value
instead of test['value']
.
Here is an example:
if (Number(test.value)) test.value += 10;
else test.value = 10;
// Or more neatly:
test.value = +test.value ? test.value + 10 : 10;
Because test['value']
is undefined
. Adding a number to undefined
will give you NaN
(which stand for "Not a Number"). You need to initialize the value before adding to it:
var test = {};
test['value'] = 0;
test['value'] += 10;
Since you are using an object you can also use the dot notation:
var test = {};
test.value = 0;
test.value += 10;
test['value'] += 10;
is equivalent totest['value'] = test['value'] + 10;
but, test['value']
is undefined, because you haven't initialized it yet
Check if test value is not undefined before adding the value:
test['value']? test['value']+=10 : test['value']=10
Why does JavaScript behave like this?
Because when the property does not exist, accessing it defaults to undefined
; and when adding a number to undefined
you get NaN
back.
How can I get this to work without initializing
result['value'] = 0
?
If you don't want to (or can't) initialize it once, you will need to check every time whether the property exists, basically:
test.value = ('value' in test ? test.value : 0) + 10;
Another approach would be to cast the property to a number every time before adding to it:
test.value |= 0;
test.value += 10;
来源:https://stackoverflow.com/questions/28367754/assigning-using-gives-nan-in-javascript