开发者

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

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,开发者_JAVA百科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?


just use the built-in join function.

str.join(',');


Check out join function

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

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

would output:

apple,orange,banana


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.


You need this

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


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

var newstr = str.join();


You're looking for array.join i believe.

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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜