Assigning using += gives NaN in javascript

六月ゝ 毕业季﹏ 提交于 2019-12-06 01:22:24
Blazemonger

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;
Lewis

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 to
test['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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!