split - JavaScript Join inserts comma delimiter when only one item in array - Stack Overflow

I'm filtering XHTML classes; when there is only a single class it inserts a ma at the beginning. T

I'm filtering XHTML classes; when there is only a single class it inserts a ma at the beginning. This makes classes that are hidden to have a value ",hidden" which ends up displaying hidden content. What am I missing? No frameworks please, I never use them.

var d = new Array();

for (var i=0;i<c.length;i++)
{
 if (c[i]==c1) {d.push(c2);}
 else if (c[i]==c2) {d.push(c1);}
 else if (c[i]!='') {d.push(c[i]);}
}

d.join(' ');
alert(d);

I'm filtering XHTML classes; when there is only a single class it inserts a ma at the beginning. This makes classes that are hidden to have a value ",hidden" which ends up displaying hidden content. What am I missing? No frameworks please, I never use them.

var d = new Array();

for (var i=0;i<c.length;i++)
{
 if (c[i]==c1) {d.push(c2);}
 else if (c[i]==c2) {d.push(c1);}
 else if (c[i]!='') {d.push(c[i]);}
}

d.join(' ');
alert(d);
Share Improve this question edited May 15, 2018 at 8:23 Cœur 38.8k25 gold badges206 silver badges278 bronze badges asked Nov 18, 2011 at 1:55 JohnJohn 13.8k15 gold badges111 silver badges192 bronze badges 1
  • 1 Um, you are alerting d and not d.join(' '). Try alerting d.length; I bet it's 2. – Raymond Chen Commented Nov 18, 2011 at 2:04
Add a ment  | 

3 Answers 3

Reset to default 3

You probably have an Array, of which there is an undefined, null or empty string as the first member, which is having its toString() called somewhere (perhaps implicitly), which calls its join() and the default joiner is the ma (,), resulting in a string with a ma at the start.

>>> [null,'hidden'] + '';
",hidden"

d is still an array after using join(). Store the result of join() in a variable to get the resulting string:

joined=d.join(' ');
alert(joined);

You could use something like:

if (d.length == 1) {
    alert(d[0].substr(1, d[0].length));
}

to clear the first sign.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745319862a4622394.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信