admin管理员组

文章数量:1393367

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 acplish the same thing. One uses a while loop and the other uses a for loop. If there's a difference between being able to acplish 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);

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 acplish the same thing. One uses a while loop and the other uses a for loop. If there's a difference between being able to acplish 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);
Share Improve this question edited Oct 13, 2015 at 2:04 Stymieceptive asked Oct 10, 2015 at 4:35 StymieceptiveStymieceptive 211 silver badge6 bronze badges 1
  • 4 you want the console output to be one line, or the code to be one line? – Jaromanda X Commented Oct 10, 2015 at 4:37
Add a ment  | 

2 Answers 2

Reset to default 4

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

本文标签: JavaScript Console Output to Single Line with For and While LoopStack Overflow