Print An Output In One Line Using Console.log()
Is it possible to print the output in the same line by using console.log() in JavaScript? I know console.log() always returns a new line. For example, have the output of multiple c
Solution 1:
in nodejs there is a way:
process.stdout
so, this may work:
process.stdout.write(`${index},`);
where: index
is a current data and ,
is a delimiter
also you can check same topic here
Solution 2:
You could just use the spread operator ...
var array = ['a', 'b', 'c'];
console.log(...array);
Solution 3:
Couldn't you just put them in the same call, or use a loop?
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
Solution 4:
So if you want to print numbers from 1 to 5 you could do the following:
var array = [];
for(var i = 1; i <= 5; i++)
{
array.push(i);
}
console.log(array.join(','));
Output: '1,2,3,4,5'
Array.join(); is a very useful function that returns a string by concatenating the elements of an array. Whatever string you pass as parameter is inserted between all the elements.
Hope it helped!
Solution 5:
You can also use the spread operator (...)
console.log(...array);
The "Spread" operator will feed all the elements of your array to the console.log
function.
Post a Comment for "Print An Output In One Line Using Console.log()"