我试图实现while和do while循环,而不使用实际数组来打印数字列表。这是我的代码和我想要的输出。我的代码
console.log("While Loop")
let j = 0;
while(j < 5){
j += 1;
console.log (j);
}
console.log("Do While Loop")
var i = 0; //set varible i = 0
do {
i += 1; //return i + 1 to i
console.log (i);
}
while (i < 5); //where i suppose to less than 5我想要的实际产出:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1发布于 2021-08-10 18:02:54
这里有两件事:
console.log()进行打印。这是因为console.log()将追加一个换行符.下面的示例将打印三角形的前半部分。
console.log("While Loop")
let j = 1;
while (j <= 5) {
let k = 1;
let str = "";
while (k <= j) {
str += k + " ";
k++;
}
j += 1;
console.log(str);
}
如果您正在使用Node.js,您可以使用process.stdout.write打印到同一行,然后在需要时显式地写入换行符。
console.log("While Loop")
let j = 1;
while (j <= 5) {
let k = 1;
while (k <= j) {
process.stdout.write(k + " ");
k++;
}
j += 1;
process.stdout.write("\n");
}https://stackoverflow.com/questions/68731384
复制相似问题