Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

for loop - JavaScript For Drill

my code isn't running, I need to get two numbers and print all the numbers between them. that is the code:

<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript">
        var minNum = window.prompt("Enter min number:");
        var maxNum = window.prompt("Enter max number:");
        if (maxNum - minNum != 1 && maxNum > minNum)
        {
            for (i = (minNum + 1); i < maxNum; i++)
            {
                document.write(i + "<br />");
            }
        }
    </script>
</body>
</html>
question from:https://stackoverflow.com/questions/65600242/javascript-for-drill

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have two issues:

First, you are using document.write() which should not be used as it will cause any previously loaded document to be thrown out and a new one created every time you use it. document.write() is a very old API that has very limited uses in modern JavaScript code. Instead, you should write the value to a pre-existing element that is already on the page.

Second, all data in HTML is strings. To use them as numbers in JavaScript, you have to convert them (either implicitly or explicitly). There are several ways to do this, but one way is to prepend the string with +.

<html>
<head>
    <title></title>
</head>
<body>
  <!-- The output from the script will be placed
       within this element. -->
  <div></div>
  
  <!-- The default type for a script is JavaScript, so you don't 
       need to write that. -->
  <script>
    // Get a reference to the div
    const output = document.querySelector("div");
    
    // window is the global object in a browser and
    // so you can omit explicitly stating it
    var minNum = +prompt("Enter min number:");
    var maxNum = +prompt("Enter max number:");
    
    if (maxNum - minNum != 1 && maxNum > minNum) {
      for (i = (minNum + 1); i < maxNum; i++){
         // To be able to have the HTML portion parsed
         // as HTML, use .innerHTML on the output element.
         // Also, to make the new value be appended to 
         // the current value, we use += instead of =.
         output.innerHTML += i + "<br>";
      }
    }
  </script>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...