使用+ =进行赋值会在JavaScript中产生NaN [英] Assigning using += gives NaN in javascript

查看:101
本文介绍了使用+ =进行赋值会在JavaScript中产生NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用+=运算符将数字分配给属性会在JavaScript中为我提供NaN.

Assignment a number to an attribute using the += operator gives me NaN in JavaScript.

此代码可以正常工作:

> var result = {};
undefined
> result['value'] = 10;
10
> result['value'] += 10;
20

但是在这里我们得到NaN:

> var test = {};
undefined
> test['value'] += 10;
NaN

JavaScript为什么会这样表现?如何在不初始化result['value'] = 0的情况下使其工作?

Why does JavaScript behave like this? How can I get this to work without initializing result['value'] = 0?

推荐答案

您无法在JavaScript中为undefined添加数字.如果您不想初始化数字,则需要测试它是否为undefined 在递增之前:

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;

这篇关于使用+ =进行赋值会在JavaScript中产生NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆