Reputation: 17849
I have a loop that prints the contents of an array with a space between each element, except for after the final element, in which case only a new line is required.
However my implementation feels "crufty" to me and I'm sure there's a more elegant way to write this, hopefully using some handy javascript trick previously unknown to me.
Here is my loop:
for(var k=0; k<cycle1.length; k++){ process.stdout.write(cycle1[k]); if(k<cycle1.length-1){ process.stdout.write(' '); }else{ process.stdout.write('\n'); } }
Upvotes: 1
Views: 177
Reputation: 15397
Assuming cycle1 is an array, use array.join
process.stdout.write(cycle1.join(" ") + "\n");
It does just what you want - takes an array, and adds the separator that you pass as an argument between each element.
Upvotes: 9