簡體   English   中英

"使用 console.log() 在一行中打印輸出"

[英]Print an output in one line using console.log()

是否可以在 JavaScript 中使用console.log()<\/code>在同一行打印輸出? 我知道console.log()<\/code>總是返回一個新行。 例如,讓多個連續console.log()<\/code>調用的輸出為:

"0,1,2,3,4,5,"

在 nodejs 中有一種方法:
進程標准輸出
所以,這可能有效:
process.stdout.write(`${index},`);
其中: index是當前數據, ,是分隔符
你也可以在這里查看相同的主題

你可以只使用傳播運算符...

 var array = ['a', 'b', 'c']; console.log(...array);

你不能把它們放在同一個調用中,或者使用循環嗎?

var one = "1"
var two = "2"
var three = "3"

var combinedString = one + ", " + two + ", " + three

console.log(combinedString) // "1, 2, 3"
console.log(one + ", " + two + ", " + three) // "1, 2, 3"

var array = ["1", "2", "3"];
var string = "";
array.forEach(function(element){
    string += element;
});
console.log(string); //123

因此,如果您想打印 1 到 5 之間的數字,您可以執行以下操作:

 var array = []; for(var i = 1; i <= 5; i++) { array.push(i); } console.log(array.join(','));

輸出:'1,2,3,4,5'

Array.join(); 是一個非常有用的函數,它通過連接數組元素返回一個字符串。 您作為參數傳遞的任何字符串都會插入到所有元素之間。

希望有幫助!

您可以只在同一行中console.log字符串,如下所示:

console.log("1" + "2" + "3");

要創建一個新行,請使用\\n

console.log("1,2,3\n4,5,6")

如果您在 node.js 上運行您的應用程序,您可以使用ansi 轉義碼來清除行\\

console.log("old text\u001b[2K\u001b[0Enew text")

直接在瀏覽器環境中是不可能的。 您需要創建一些緩沖區來保存要在同一行上打印的值。

在以前的答案中有使用數組和循環的示例。 作為替代方案,您可以在功能上解決它:

 const print = ((buffer = '') => arg => { if (arg !== '\\n') { buffer += arg } else { console.log(buffer) buffer = '' } })() print('x') print('y') print('z') print('\\n') // flush buffer

或者您可以使用對象設置器

 const c = { buffer: '', set log(val) { if (val !== '\\n') { this.buffer += val } else { console.log(this.buffer) this.buffer = '' } } } c.log = 'foo' c.log = 42 c.log = 'bar' c.log = '\\n'

您可以將它們打印為數組

如果你寫:

console.log([var1,var2,var3,var4]);

你可以得到

[1,2,3,4]

您還可以使用擴展運算符(...)

console.log(...array);

“Spread”運算符會將數組的所有元素提供給console.log函數。

您可以使用擴展運算符。 “log”方法將它的參數打印在一行中,您可以通過展開數組將數組的元素作為單獨的參數提供給它。

console.log(... array);

您可以使用逗號分隔符:

console.log(1,2,3,4);

但是如果您希望逗號出現在輸出中,那么您將需要使用字符串:

console.log('1,','2,','3,','4');

你也可以這樣做:

 let s = ""; for (let i = 0; i < 6; i++) { s += i.toString(); if (i != 5) { s += ","; } } console.log(s);

你可以這樣做。 這很簡單。

    var first_name = ["Ram", "Sita", "Hari", "Ravi", "Babu"];
    name_list = "";
    name_list += first_name;
    console.log(name_list);
    // OR you can just typecast to String to print them in a single line separated by comma as follows;
    console.log(first_name.toString());
    // OR just do the following
    console.log(""+first_name);
    // Output: Ram,Sita,Hari,Ravi,Babu

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM