[英]Javascript: Average of 2 user input values
对于这个基本问题,我深表歉意,但我长期以来一直试图让这项工作正常进行,但我似乎无法让这段代码返回一个值。
我很尴尬地承认我已经尝试了多长时间,以及我看过多少相关的 StackOverflow 问题,但是,没有一个像我的代码那么简单,当我试图做一些更接近于我的看起来,它只是不会提醒任何东西。
思路如下:
无论我进行了多少次迭代,我的警报都是 NaN。 我真的可以使用一些建议。 提前致谢!
<html> <head> <title> Javascript </title> <body> <p> Enter two number for an average below </p> <p> Number 1<input type="text" id="userInput1"></input></p> <p> Number 2<input type="text" id="userInput2"></input></p> <button id="averageButton"> Calculate</button> <script type="text/javascript"> function average(a, b) { return ((a + b) /2); } document.getElementById("averageButton").onclick = function (){ var a = document.getElementById("userInput1").value; var b = document.getElementById("userInput2").value; alert(average()); } </script> </body> </html>
您未能将数字 a,b 传递给您的函数 - 一个简单的错误。
但由于输入被视为字符串,您还需要将它们转换为数字 a*1
见注释代码
<html> <head> <title> Javascript </title> <body> <p> Enter two number for an average below </p> <p> Number 1<input type="text" id="userInput1"></input></p> <p> Number 2<input type="text" id="userInput2"></input></p> <button id="averageButton"> Calculate</button> <script type="text/javascript"> function average(a, b) { // force the input as numbers *1 return ((a*1 + b*1) /2); } document.getElementById("averageButton").onclick = function (){ var a = document.getElementById("userInput1").value; var b = document.getElementById("userInput2").value; // pass the numbers to the average function! alert(average(a,b)); } </script> </body> </html>
乍一看,您可能需要将输入值从字符串转换为浮点数,然后将它们实际传递给平均函数。
您可能希望将输入更改为<input type="number">
以防止用户添加非数字值。
其次将您的输入解析为document....value
返回字符串,
var a = parseFloat(document.getElementById("userInput1").value);
var b = parseFloat(document.getElementById("userInput2").value);
如果你这样做,你就不必处理做a*1
的有趣事情了。
// force the input as numbers *1
return ((a*1 + b*1) /2);
不需要此块,因为将字符串与数字相乘会返回 NaN 值。
function average(a, b) { return ((a + b) / 2); } document.getElementById("averageButton").onclick = function() { var a = document.getElementById("userInput1").value; var b = document.getElementById("userInput2").value; alert(average()); }
<p> Enter two number for an average below </p> <p> Number 1<input type="text" id="userInput1"></input> </p> <p> Number 2<input type="text" id="userInput2"></input> </p> <button id="averageButton"> Calculate</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.