javascript - 为什么我的 JavaScript 代码算术方程出现 NaN 错误
问题描述
我正在尝试为一项任务创建一个婚礼宴会桌规划器应用程序,但我的“table”变量出现 NaN 错误,但我的 return 语句中的“guests”变量却没有。图片是我在我的网站上得到的,下面是脚本代码。我正在使用带有 JavaScript 的 HTML 语言。谢谢你的帮助!
function distribGuests() {
// Read the table value inputed by the user
var text = document.getElementById('tablesInputBox').value;
// Convert what the user typed from text into a number.
var t = (text);
// Read the guests value inputed by the user
var text = document.getElementById('guestsInputBox').value;
// Convert what the user typed from text into a number.
var g = (text);
// Formula for variable "a", the rounded down value of guests
var a = Math.floor (g / t);
// Formula for variable "b", the rounded up value of guests
var b = Math.round (g / t);
// Formula for variable "x", the end result for the first set of table distributions
var x = (g - b * t) / (a - b);
// Formula for variable "y", the end result for the second set of table distrubutions
var y = (t - x);
// Use string concatenation to produce statement for end result of wedding table distribution
var message = "There will be "+ x +" tables with "+ b +" guests and "+ y +" tables with "+ a +" guests";
// Display the message in the div that has the outputDiv
document.getElementById('outputMessage').innerHTML = message;
}
解决方案
括号不会将字符串转换为数字。
// Convert what the user typed from text into a number.
var t = (text);
应该:
// Convert what the user typed from text into a number.
var t = +text;
您也可以使用parseInt(text)
, 但+text
对于您的用例来说实际上是相同的(称为类型强制)。
(关于这两种方法的区别分析,请看这个问题)
推荐阅读
- python - 信号 QscrollArea
- amazon-web-services - 使用 IF 函数检查是否设置了参数,而无需创建条件
- javascript - 将 CreateElement 转换为反引号不起作用
- r - 根据配对列替换值
- git - “错误:找不到满足的版本......”尽管没有为包提供特定版本。为什么以及如何绕过它?
- javascript - 意外的令牌 { 从 Flask 获取数据到 JavaScript
- logging - 如何将 GCS 审计日志发送到 logstash?
- reactjs - 更新许多使用 Mongoose 的条件
- c++ - Windows 包含文件夹中缺少 vcruntime.h?
- spring-batch - 使用for循环批量遍历子目录