简体   繁体   English

在 JavaScript 中中断 for 循环

[英]Break for loop in JavaScript

I want to break my for loop that I have 10 numbers in a line.我想打破我的 for 循环,因为我在一行中有 10 个数字。

for(var i = 100; i <=300; i++){
    console.log(i);
}

I guess by "that I have 10 numbers in a line."我猜是“我在一行中有 10 个数字”。 you mean to break the line after 10 printed numbers.你的意思是在 10 个打印数字后换行。 It seems not to be possible to log to the console without a linebreak, so you have to concatenate the output until 10 outputs are concatenated.似乎不可能在没有换行符的情况下登录到控制台,因此您必须连接输出,直到连接 10 个输出。

var line = '';              // initialize line variable
for(var i = 100; i <=300; i++) {
    line += i               // append current value to the line without printing it
    if ((i%10) === 0) {       // check, if the current iteration is dividable by 10
        console.log(line);    // output the collected output
        line = ''             // reset the line var
    }
}
if (line !== '') console.log(line);    // if the total count was not dividable
                                       // by 10, output the left over

In response to your statement, "My loop starts from 100, when it gets to 110, it breaks and skip a line. And continue reading when it reaches 120, skips a line:回应您的声明,“我的循环从 100 开始,当它到达 110 时,它会中断并跳过一行。并在达到 120 时继续阅读,跳过一行:

        for(let i = 100; i <=300; i++){                         
            if(i % 10 == 0) {               
                continue;
            }           
            console.log(i);
        }

A break will exit the loop completely, a continue will skip to the next iteration. break将完全退出循环, continue将跳到下一次迭代。 This skips every loop iteration that's divisible by 10.这将跳过可被 10 整除的每个循环迭代。

you can use if condition inside your for loop lets say if you want to break the loop after 10 numbers printed just add this line in your for loop您可以在 for 循环中使用 if 条件,假设您想在打印 10 个数字后中断循环,只需在 for 循环中添加这一行

if(i==10)
{
   break;
}

The break condition will bring you out of the for loop.中断条件将使您退出 for 循环。

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

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