node.js - 在node.js中添加值

标签 node.js express

enter image description here

上面是下面代码片段的结果

 var total_points = 0
for(var i = 0; i < req.body.requisites.length; i++){

    total_points = total_points + req.body.requisites[i].points
    console.log(req.body.requisites[i].points ,  total_points)
}
console.log('total points :' + total_points)
req.body.points = total_points

我不明白为什么一次它连接结果(查看“总分”之前的最后一个值)而下一次它计算正确。

如果您能提供帮助,我们将不胜感激。

提前致谢!

最佳答案

根据我之前的评论,您的某些输入似乎必须是字符串而不是数字,并且由于 Javascript 的强制规则,在添加字符串和数字时您会得到字符串连接而不是数学加法。

您可以强制将所有输入强制输入数字,这样您总是会得到如下所示的加法:

var total_points = 0
for (var i = 0; i < req.body.requisites.length; i++) {
    total_points = total_points + (+req.body.requisites[i].points);
    console.log(req.body.requisites[i].points ,  total_points)
}
console.log('total points :' + total_points)
req.body.points = total_points

而且,使用 .reduce() 可能会更容易:

req.body.points = req.body.requisites.reduce((total, val) => total + (+val)), 0);

如果它是数字字符串,则(+req.body.requirements[i].points)(+val) 将其转换为数字。

关于node.js - 在node.js中添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51583265/

相关文章:

node.js - gulp.watch 任务抛出错误 : (FSEvents. 框架)FSEventStreamStart:register_with_server:错误

node.js - 如何将 Node 和 Express 与 coffeescript 和 requirejs 一起使用?

javascript - 在 AngularJS 和 Node 作为后端发送 sendgrid 电子邮件时未调用 app.post 方法

mysql - 如何将我的 MEAN 应用程序转换为使用 mySQL

javascript - TypeError : data. 过滤器不是函数

javascript - 根据来自 php 脚本的作业订单安排 cron 作业的更好方法

javascript - 如何使用javascript过滤数组中的所有字符串序列

node.js - 使用 node.js 将文件从 S3 上传到 Youtube

javascript - CouchApp 与 Node.js

node.js - 如何设置 cookies express, react.js