Trindaz
Trindaz

Reputation: 17849

Is there a more elegant way to write this loop?

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

Answers (2)

falinsky
falinsky

Reputation: 7428

you can use join method:

cycle1.join(' ') + '\n';

Upvotes: 2

Scott Mermelstein
Scott Mermelstein

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

Related Questions