我如何使用窗口对象,将两个数字相加/求和,我目前得到的例子-(我可以将两个数字相加,但不能使其等于总和?)
<html>
<head>
<script language="JavaScript">
var requestMsg = "Enter a number";
userInput1 = prompt(requestMsg);
requestMsg = "Enter another number here";
userInput2 = prompt(requestMsg);
alert(total = " You entered " + userInput1 + " + " + userInput2 + " which equals ");
</script>
<head>
<body>
</body>
</html>
您必须将其转换为数字,因为prompt返回字符串,我也建议使用模板字符串,如下面的代码片段所示。
使用模板字符串,您可以摆脱字符串连接,这允许您编写更具可读性的代码。
<html>
<head>
<script language="JavaScript">
var requestMsg = "Enter a number";
userInput1 = prompt(requestMsg);
requestMsg = "Enter another number here";
userInput2 = prompt(requestMsg);
alert(`You entered ${userInput1} ${userInput2} which equals ${Number(userInput1) + Number(userInput2)} `);
</script>
<head>
<body>
</body>
</html>
所以我猜你面临的问题是,当你添加输入(例如:3,2)你得到32而不是5。这是因为prompt()
检索到的输入是一个字符串,需要将其转换/类型转换为一个数字。您可以通过Number(input)
或parseInt(input, "10")
函数来完成此操作。
alert(total = " You entered " + userInput1 + " + " + userInput2 + " which equals " + (Number(userInput1) + Number(userInput2)));