我在下面的代码中有一个SQL查询。我正在尝试使用for循环在查询中添加Totalcost列的值。当我尝试运行该程序时,我得到的是NaN,它只打印一次时会打印6次
我使用rows [0] .Totalcost来获取我想要的列,并且它仅打印结果的第一行。然后,我使用循环将其添加到totalcost变量中。当我在控制台日志中返回NaN
router.get("/requestvoucher/:rvnumber/:status/:to", isLoggedIn, function(req, res){
var reqvoucher = req.params.rvnumber;
var status = req.params.status;
var to = req.params.to;
var totalcost;
var sql = `SELECT Itemname, Itemcode, Quantity, Totalcost, Description, Brand, Category, RVnumber, Requestto,Requeststatus FROM billingdata.rvrequest WHERE rvnumber=?`;
query = db.query(sql,[reqvoucher], function(err, rows){
if (err) {
throw err;
}else{
//console.log(rows[0].Totalcost);
//My Console.logs prints 6 times i have no idea why
for (var i = 0; i < rows.length; i++) {
var totalcost =+ rows[0].Totalcost[i];
}
console.log(totalcost);
res.render('updaterequest', {dataUpdate: rows, rvNumber: reqvoucher, reqStats: status, reqto: to});
}
});
});```
I'm expecting the sum of the Totalcost column using for loop and printed it once.
答案 0 :(得分:0)
只需更换
Just
与var totalcost =+ rows[0].Totalcost[i];
还有一个。看起来像您的行[0]。Totalcost[i]有时不是数字。因此,您的总和可以为var totalcost += rows[0].Totalcost[i];
。为了防止这种情况,您可以使用类似
NaN