![](/img/trans.png)
[英]How to print on one line after applying a for loop in javascript?
[英]Javascript for loop console print in one line
我正在嘗試從我的 for 循環中獲取 output 以在控制台中打印一行。
for(var i = 1; i < 11; i += 1) {
console.log(i);
}
現在是
1
2
3
4
5
6
7
8
9
10
我怎樣才能在一行中得到 output (像這樣1 2 3 4 5 6 7 8 9 10
)?
構建一個字符串,然后在循環后記錄它。
var s = ""; for(var i = 1; i < 11; i += 1) { s += i + " "; } console.log(s);
在 Node.js 中,您還可以使用以下命令:
process.stdout.write()
這將允許您避免向作用域添加填充變量,而只需打印 for 循環中的每個項目。
沒問題,只需將它們連接到一行即可:
var result = ''; for(var i = 1; i < 11; i += 1) { result = result + i; } console.log(result)
或更好,
console.log(Array.apply(null, {length: 10}).map(function(el, index){ return index; }).join(' '));
繼續前進並學習東西! 祝你好運!
可以有一種在單行中打印計數器的替代方法,console.log() 在不指定的情況下放置尾隨換行符,我們不能省略它。
let str = '',i=1; while(i<=10){ str += i+''; i += 1; } console.log(str);
// 1 to n const n = 10; // create new array with numbers 0 to n // remove skip first element (0) using splice // join all the numbers (separated by space) const stringOfNumbers = [...Array(n+1).keys()].splice(1).join(' '); // output the result console.log(stringOfNumbers);
let n=0;
for ( i = 1; i <= 10; i++)
{
n += i + “ “;
console.log(n);
}
或者,要在單行中打印,您可以在 Javascript 中使用重復 -
for(let j = 0; j < 5; j++){
console.log('*'.repeat(j))
}
只需將console.log()
更改為process.stdout.write()
。
nb:如果你使用的是Nodejs
或者,您也可以像這樣嘗試
程序
let s = '';
for(let i = 1; i < 11; ++i) {
s += `${i} `;
}
console.log(s);
Output
1 2 3 4 5 6 7 8 9 10
非常規方法; 將元素添加到數組中並使用傳播運算符將您的值傳播到單個控制台日志中
const arr = []
for (let i = 1; i <= 5; i++){
arr.push(i)
}
console.log(...arr)
我們可以使用process.stdout.write()
方法打印到控制台而無需尾隨換行符。 它只接受字符串作為參數,但在這種情況下i + " "
是一個字符串,所以它可以工作:
for (var i = 1; i < 11; i += 1) {
process.stdout.write(i + " ");
}
注意:它僅適用於 Node.js。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.