我有下面的代码与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.
分析解答

只需更换 var totalcost =+ rows[0].Totalcost[i];var totalcost += rows[0].Totalcost[i];

而另一个。看起来像你的行[0] .Totalcost [i]有时候不是数字。因此,您的总和可以是NaN。为了防止这种情况,你可以使用像 totalcost+=isNaN(rows[0].Totalcost[i])?0:rows[0].Totalcost[i]