简体   繁体   English

node.js 中的 While 循环

[英]While loop in node.js

I am trying to convert a C# snippet for a simple while loop to a JavaScript solution.我正在尝试将用于简单 while 循环的 C# 片段转换为 JavaScript 解决方案。 The C# code asks for a input, prints the output, and as long as the input is not 0, continues the question. C# 代码要求输入,打印 output,只要输入不为 0,继续提问。

For the JavaScript solution, I am using VS Code and the integrated terminal for the JS output using node.对于 JavaScript 解决方案,我使用 VS Code 和使用节点的 JS output 的集成终端。 As I understand, when using node and the readline method, I can't use while loops?据我了解,在使用节点和 readline 方法时,我不能使用 while 循环? But resort to if and switch case?但是求助于 if 和 switch case?

This is my C# code:这是我的 C# 代码:

    public void WriteNumbers(int i)
    {
        while(i != 0)
        {
            PrintWriteNumbers();
            break;
        }
    }

    public void PrintWriteNumbers()
    {
       Console.WriteLine("Provide a number: ");
       WriteNumbers(int.Parse(Console.ReadLine()));
    }

Can I get this kind of behavior in the terminal with JavaScript or create a html page?我可以使用 JavaScript 在终端中获得这种行为或创建 html 页面吗?

I started to use a html output for my JavaScript, this is code, but it is incomplete:我开始为我的 JavaScript 使用 html output,这是代码,但它不完整:

<h2>JavaScript While Loop</h2>

<p id="demo"></p>

<script>
let text = ""
let num
        while (num !== 0) {
            num = parseInt(prompt("write a number"))
            text += "<br>The number is " + num
            break
        }
        document.getElementById("demo").innerHTML = text
</script>

It does take in a number and prints it to the screen.它确实接收一个数字并将其打印到屏幕上。 What I want to actually do is to print the output to the p tag, and if the input is not 0, initiate the prompt again for a new input, and exit the prompt when it is 0.我实际要做的是将output打印到p标签,如果输入不为0,则再次启动提示输入新的输入,为0时退出提示。

Your while loop should be written like this,你的while循环应该这样写,

while (num !== 0) {
    num = parseInt(prompt("write a number"))
    if(num === 0) break;
    text += "<br>The number is " + num
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM