Amit Pal
Amit Pal

Reputation: 11052

How to use join (in built method) in javascript?

In javascript loop i am generating a xml like this:

for (m = 0; m < t.length; m++) {
     var arr1 = t[m].split("\t");
     s = "'<row dc= '" + arr1[0] + "' al='" + arr1[1] + "' msg='" + arr1[2] + "' />'";
     alert(s);
     //s = s.join(' '); 
    }

Forgot about the t variable and all. by run this code i am getting the s value in the following format:

<row dc = "abc" al="56" msg="dkaj" />

In the second iteration it shows like this:

<row dc = "abwwc" al="56w" msg="dkajad" />

and so on till the m<t.length satisfy. What i want to join the list in each iteration. After joining all of them i should get in this way:

<row dc = "abc" al="56" msg="dkaj" /><row dc = "abwwc" al="56w" msg="dkajad" /> and so on..

I tried to do it with join written in comment section, but didn't work for me. What i am doing wrong?

Upvotes: 4

Views: 170

Answers (1)

Matt
Matt

Reputation: 75317

The best way would be to define a string outside the loop an append to it;

var v = '';
for (m = 0; m < t.length; m++) {
     var arr1 = t[m].split("\t");
     s = "'<row dc= '" + arr1[0] + "' al='" + arr1[1] + "' msg='" + arr1[2] + "' />'";
     alert(s);
     v += s;
    }

alert(v);

If you still want to use join(), make v an array and push() elements on to it (note that join() is an array method, not for string's)

var y = [];
for (m = 0; m < t.length; m++) {
     var arr1 = t[m].split("\t");
     s = "'<row dc= '" + arr1[0] + "' al='" + arr1[1] + "' msg='" + arr1[2] + "' />'";
     alert(s);
     y.push(s);
    }

alert(y.join(''));

You'll be pleased to see I've tried to adhere to your variable naming conventions in my examples (i.e. meaningless characters).

Upvotes: 2

Related Questions