简体   繁体   中英

JavaScript Console Output to Single Line with For and While Loop

I need to figure out how to output a list of numbers in a loop to the console. However, the output to the console must be in the same line, as opposed cascading down the page with every new number. Below, I have two separate blocks of code that accomplish the same thing. One uses a while loop and the other uses a for loop. If there's a difference between being able to accomplish this in a for loop versus a while loop, I'd like to know that as well. Thank you.

While Loop

var number = 2;

while (number <=10) {
console.log(number++);
number = number + 1;
}

For Loop

for (var number = 2; number <= 10; number = number + 2)
console.log(number);

To keep it simple, all you need to do is concatenate the numbers to a string that you keep track of. Every time you console.log, it will automatically move it to a new line.

var output = ""; 
for (var i = 2; i <= 10; i = i + 2) {
    output += i + " "; 
}
console.log(output);

The type of loop you use doesn't matter.

While:

var number = 2, output = [];
while (number <=10) {
    output.push(number++);
    number = number + 1;
}
console.log.apply(console, output);

For:

var number, output=[];
for (number = 2; number <= 10; number = number + 2) {
    output.push(number);
}
console.log.apply(console, output);

Note, I would recommend you don't do for(var x... - it gives a false sense of scope for the var x - but that's just opinion on my part

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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