I want to print a list (var lst=[1,2,3,4,5]) using a loop on the same line. Can I do that in JavaScript ?
6 Answers
You could use Function#apply or spread syntax ....
var list = [1, 2, 3, 4, 5];
console.log.apply(null, list); // traditional
console.log(...list); // ES6
Comments
The exact behavior of console.log is not specified by ECMAScript, so it varies from implementation to implementation, but it is intended to be used for logging events. The fact that each event usually becomes a single line in a web browser's console window led it to be the Node.js equivalent of "println", but outside the context of a specific implementation its behavior is not predictable.
You can pass multiple parameters to log, in which case most (but not all) implementations will print them all out on the same line separated by whitespace. So if you're using one of those implementations, and you have a list and just want all the elements on one line separated by space, you can use apply to call the method as if each element of the list was a separate argument:
console.log.apply(console, lst);
Caveat: if the first argument is a string that contains what look like Formatter format control sequences (%s, etc.), it will be parsed as such and the remaining arguments used to fill in those slots.
But the most reliable way to achieve the desired result is to build a single string yourself representing what you want the final line to look like, and then call console.log exactly once with that string as the argument.
1 Comment
You could do it easily by using the join() function which can be used on any array in JavaScript!
For example:
var lst = ["check","word","3","could","hello"]
console.log(lst.join())
source-code:
https://jsfiddle.net/Lpdurxsb/
console.log.apply(null, lst);.console.log(JSON.stringify(lst))?