Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append (connect) strings to construct a new string?

Tags:

javascript

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?

like image 826
Mellon Avatar asked Dec 05 '22 22:12

Mellon


2 Answers

just use the built-in join function.

str.join(',');
like image 167
El Guapo Avatar answered Dec 30 '22 21:12

El Guapo


Check out join function

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

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

would output:

apple,orange,banana
like image 36
KJYe.Name Avatar answered Dec 30 '22 19:12

KJYe.Name