如何在javascript中进行类型转换?

时间:2014-07-10 04:48:20

标签: javascript

我正在尝试添加我的数据总数:

[{"sector": "Basic drinking water supply and basic sanitation", "budget": 558733.7, "no": 8},
{"sector": "Culture and recreation", "budget": 1550000.0, "no": 2},
{"sector": "Roads", "budget": 1221142.04, "no": 4},
{"sector": "Agriculture", "budget": "", "no": 1},
{"sector": "Health", "budget": "", "no": 4},
{"sector": "Education", "budget": 473379.58, "no": 6},
{"sector": "Energy generation & supply", "budget": 584624.55, "no": 1},
{"sector": "Agricultural water resources", "budget": 40000.0, "no": 1}]

所以我的代码是这样的:

for(i=0;i<data.length;i++){
data[i]["budget"]= +data[i]["budget"];
console.log(+data[i]["budget"]);
end_val+= data[i]["budget"];
console.log(end_val);
}

但输出是字符串的连接。为什么javascript没有将我的值强制转换为整数?我也试过parseInt()

5 个答案:

答案 0 :(得分:1)

Array.prototype.reduce应该轻松总结一切

var sum = data.reduce(function(sum, row) {
  return sum += Number(row.budget);
}, 0);

至于字符串问题,那是因为某些行有{budget: ""}而引起的。在JavaScript中将string添加到float时,它将变为字符串。额外的“添加”将是字符串连接。

注意:这需要ECMAScript >= 5

答案 1 :(得分:1)

您想要将所有预算合计吗?

您需要使用parseFloat进行投射,并使用isNaN检查解析后的值是否为数字。

var data = [
    {"sector": "Basic drinking water supply and basic sanitation", "budget": 558733.7, "no": 8},
    {"sector": "Culture and recreation", "budget": 1550000.0, "no": 2},
    {"sector": "Roads", "budget": 1221142.04, "no": 4},
    {"sector": "Agriculture", "budget": "", "no": 1},
    {"sector": "Health", "budget": "", "no": 4},
    {"sector": "Education", "budget": 473379.58, "no": 6},
    {"sector": "Energy generation &amp; supply", "budget": 584624.55, "no": 1},
    {"sector": "Agricultural water resources", "budget": 40000.0, "no": 1}
];

var sum = 0;
for (i=0 ; i<data.length ; i++){
    var val = parseFloat(data[i]["budget"]);
    sum += isNaN(val) ? 0 : val;
}
console.log(sum);

DEMO

答案 2 :(得分:1)

将end_val变量初始化为0.当使用increment运算符进行数字加法时,检查两个操作数是否都是Number类型。

var end_val = 0;
for(i=0;i<data.length;i++){        
     end_val+= parseFloat(data[i]["budget"]);
     console.log(end_val);
}

答案 3 :(得分:1)

如果你使用它会好得多:---&gt; Typecast.js

var sum = 0;
for (i=0 ; i<data.length ; i++){
    var val = type.num.to(data[i]["budget"]);
    sum += type.nan(val) ? 0 : val;//---->HERE You dont even need to do this validation 
}
console.log(sum);

Typecast.js--->LINK:

Typecast根据MIT许可证分发

答案 4 :(得分:0)

问题是你的一些值不是整数。

尝试使用parseFloat()

希望这有帮助。