Javascript连接数字,而不是加起来

时间:2013-02-01 22:19:43

标签: javascript titanium titanium-mobile

它一直将我的数字连接到2111而不是5.这是为什么?我尝试过使用parseInt但没有运气。 res3 btw表示我正在执行的数据库查询。

var dt_total_hours = 0;

            dt_total_hours += res3.fieldByName(dt_cost_per_hour);
            dt_total_hours += res3.fieldByName(dt_prod_dt_hours);
            dt_total_hours += res3.fieldByName(dt_prod_rate);
            dt_total_hours += res3.fieldByName(dt_cost_per_unit);
            dt_total_hours += res3.fieldByName(dt_scrap_startup_cost);
            dt_total_hours += res3.fieldByName(dt_labor_expense);
            dt_total_hours += res3.fieldByName(dt_since_issues_first_noticed);
            dt_total_hours += res3.fieldByName(dt_wo_for_maint);
            dt_total_hours += res3.fieldByName(dt_investigation);
            dt_total_hours += res3.fieldByName(dt_maint_made_bandaid);
            dt_total_hours += res3.fieldByName(dt_parts_outsourcing);
            dt_total_hours += res3.fieldByName(dt_get_equip_out_prod);
            dt_total_hours += res3.fieldByName(dt_perm_repair);
            dt_total_hours += res3.fieldByName(dt_equip_back_to_prod);
            dt_total_hours += res3.fieldByName(dt_to_full_prod_speed);
            dt_total_hours += res3.fieldByName(dt_other);

3 个答案:

答案 0 :(得分:8)

如果值是字符串,则它们将被连接,而不是以数字形式添加。

尝试constructing a number from the string value

dt_total_hours += Number(res3.fieldByName(dt_cost_per_hour));
//                ^------ Force a number here instead of a string.

答案 1 :(得分:1)

是的,它正在将它们视为字符串。我发现将它们解释为数字的肮脏,可怕的黑客攻击是x += y并将其更改为x += y / 1.0(或/ 1表示整数)。通常就是诀窍。

答案 2 :(得分:0)

您可以根据需要的类型解析数据,如下所示

dt_total_hours += parseInt(res3.fieldByName(dt_cost_per_hour));

您也可以使用parseFloat方法