最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论