4

I am currently writing a large amount of code, but I will keep it simple. I have a javascript array (possibly an object, still unsure exactly of the conventional naming), here is the initialization code:

var myArray = ["assignS" , ";" , "S"]

This is what I get as a console.log() from firebug on the element. There is too much code to post as it is assigned multiple values through many for loops. So this array (or object) is printed later as follows:

document.write("S -> " + myArray);

output:

 S -> assignS,;,S

I do not want these commas in the result, it poses problems as some elements in the array may be commas themselves. I have ruled out the .join() method because of this, and am unsure how to proceed.

3
  • 1
    Why have you ruled out the join method? That seems like the logical solution. Commented Feb 21, 2013 at 8:52
  • 1
    Using document.write can be a very bad practice, and generally array is not expected to treat as a string. Anyway, what is your expected result? Because ["assignS",";","S"].join("") returns "assignS;S". Commented Feb 21, 2013 at 8:53
  • seems like ; is your preferred glue, so: ["assignS", "S"].join(';') would work as well. Also before ruling something out, read the docs carefully. Commented Feb 21, 2013 at 9:01

4 Answers 4

26

You ruled out the join method why, exactly? It takes a parameter, the separator, which you can then use to specify no separator:

myArray.join("");

I recommend reading up on the documentation for .join(). Also, I wouldn't recommend you use document.write, it has very few good applications.

Sign up to request clarification or add additional context in comments.

Comments

3

The .join method on an array will by default concatenate all items with a comma, but it takes one argument to override this to be any other string to use as the glue - including an empty string.

myArray.join(''); // is "assignS;S"

Comments

1
var a=[1,2,3,4]
var result="";
for(i= a.length-1; i>=0;i--){
    result=a[i]+result;
}

document.getElementById("demo").innerHTML=result;

1 Comment

This answer could do with more explanation - the indentation is also not quite right.
0

Use this code:

document.write("S -> " + myArray.join(" "));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.