Javascript变量未添加,仅串联为字符串 [英] Javascript variables not adding, only concatenating as strings

查看:53
本文介绍了Javascript变量未添加,仅串联为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些简单的代码,应该将两个数字相加,并且似乎一直在将它们相加,即,如果我有一个初始化为0的变量,则一次添加100,然后再添加200,似乎将其添加为遵循0 + 100 + 100 + 200,返回400 NOT300.如何正确添加?

I have some simple code that should add two numbers and it seems to keep adding them, i.e. if I have a variable that is initialized as 0 , I add 100 once, and then I add 200, it seems to add it as follows 0 + 100 + 100 + 200, returning 400 NOT 300. How can I get this to add correctly?

function calcScores(amount) {
    amount = parseInt(amount,10);
    for(var key in teamSelection) {
        if (teamSelection[key]['Selected']) {
            score = parseInt(teamSelection[key]['Score'],10);
            var total = +score + +amount;
            teamSelection[key]['Score'] = total;
        }
    }
}

推荐答案

您应该尝试在没有其他因素的情况下以较小的比例重现该问题.在大多数情况下,通过将有问题的代码片段减少到微不足道的地方,问题就变得显而易见了.

You should try to reproduce the problem in a smaller scale, without other factors. Most of the time, by reducing the problematic snippet to something trivial, the issue becomes evident.

您还应该在问题中包括实际输出与预期输出.

You should also include in your questions the actual output vs the expected output.

现在,我能为您提供的所有帮助是在您的代码中指出两个可疑的部分:

As it is now, all I can do to help you is point out two suspicious parts in your code:

  1. parseInt可以返回NaNundefined.您不处理这些情况.

  1. parseInt can return NaN or undefined. You don't handle these cases.

total = +score + +amount有一些额外的加号,应该没什么区别,但是,这是javascript.也许total += score + amount.

total = +score + +amount has a few extra addition symbols, that shouldn't make any difference, but hey, this is javascript. Perhaps total += score + amount.

如果您需要更多帮助,则必须将问题缩小到特定的范围:_此代码将生成此输出,而不是其他输出."

If you want more help, you'll have to narrow down the problem to something specific: _this code produces this output instead of this other output".

这篇关于Javascript变量未添加,仅串联为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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