从 window 对象提示添加

adding from the window object prompt

我如何使用 window 对象,add/sum 两个数字,到目前为止我得到的示例 - (我可以将两个数字相加,但无法使其等于总和?)

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

你必须将它转换为数字,因为提示 returns 一个字符串,我也建议使用 template strings 就像下面的代码片段一样。
使用模板字符串,您可以摆脱字符串连接,从而编写更具可读性的代码。

<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() 检索到的输入是一个字符串,并且它需要 converted/typecast 变成一个数字。您可以通过 Number(input)parseInt(input, "10") 函数执行此操作。

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