1

我如何使用 window 对象来添加/求和两个数字,我到目前为止得到的示例 - (我可以添加两个数字但不能让它等于总和?)

<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>

4

2 回答 2

1

您必须将其转换为数字,因为提示返回一个字符串,我也建议使用下面代码段中的模板字符串
使用模板字符串,您可以摆脱字符串连接,从而编写更具可读性的代码。

<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>

于 2021-02-06T07:50:45.967 回答
0

所以我猜你面临的问题是,当你添加输入(例如:3、2)时,你得到的是 32 而不是 5。发生这种情况是因为检索到的输入prompt()是一个字符串,需要将其转换/类型转换为一个数字. 您可以通过Number(input)orparseInt(input, "10")函数来执行此操作。

alert(total = " You entered " + userInput1 + " + " + userInput2 + " which equals " + (Number(userInput1) + Number(userInput2)));

于 2021-02-06T07:56:46.177 回答