4

I have a array of strings:

str[1]='apple';
str[2]='orange';
str[3]='banana';
//...many of these items

Then, I would like to construct a string variable which looks like var mystr='apple,orange,banana,...', I tried the following way:

var mystr='';
for(var i=0; i<str.length; i++){
  mystr=mystr+","+str[i];
}

Which is of course not what I want, is there any efficient way to connect all this str[i] with comma?

7 Answers 7

6

just use the built-in join function.

str.join(',');
Sign up to request clarification or add additional context in comments.

Comments

4

Check out join function

var str = [];
str[0]='apple';
str[1]='orange';
str[2]='banana';

console.log(str.join(','));

would output:

apple,orange,banana

Comments

3

The fastest and recommended way of doing this is with array methods:

var str = [];

str[1] = 'apple';
str[2] = 'orange';
str[3] = 'banana';

var myNewString = str.join(',');

There have been various performance tests showing that for building strings, using the array join method is far more performant than using normal string concatenation.

Comments

2

You need this

var mystr = str.join(',');

Comments

2

how about 'join()'? e.g.

var newstr = str.join();

Comments

0

You're looking for array.join i believe.

alert(['apple','orange','pear'].join(','));

Comments

-1

Is this what you want?

var str = new Array(); //changed from new Array to make Eli happier
str[1]='apple';
str[2]='orange';
str[3]='banana';

var mystr=str[1];
for(var i=2; i<str.length; i++){
  mystr=mystr+","+str[i];
}
console.log(mystr);

would produce

apple,orange,banana

3 Comments

I don't even know what to say about this.
var str = new Array; <-- what is wrong with this statement?
@Eli just because it doesn't use the built in join() method doesn't make it wrong (and new Array still works even if it isn't totally correct), it just may not be as efficient. There have been times when I couldn't use the join() method as i needed to do more logic then just gluing together, in that case my solution would be a good one to have here so people can see a way to do it without join()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.