1

This might be very simple but I am trying to use the join() array in order to remove the - from the last item on the days array.

How can I do that? This is my code:

var days = [
  'Monday',
  'Tuesday',
  'Wednesday',
  'Thursday',
  'Friday',
  'Saturday',
  'Sunday'
];

var counter = 0;
while (counter < days.length) {
  document.write(days[counter]);
  counter++;
  days.join(' - ');
}
10
  • How is there a -? Can I see your html? Commented Sep 27, 2015 at 15:39
  • 1
    The .join() function returns a string. You just need document.write(days.join(",")); and no loop. Commented Sep 27, 2015 at 15:39
  • 1
    The default join character is comma (,) so just days.join(). Commented Sep 27, 2015 at 15:40
  • @RobG but there's an space.... join(", ") Commented Sep 27, 2015 at 15:41
  • 1
    I do not understand what the question is or what problem you're having. You call days.join() in the loop, but do nothing with the returned string so it is a pointless line of code. Further, your question text refers to removing a -, but there is no such character in your code at all. Commented Sep 27, 2015 at 15:42

1 Answer 1

5

You don't need a loop. It's very simple:

    var days = [
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday',
      'Sunday'
    ];

    document.write(days.join(", "));

I don't recommend the use of document.write. It's dangerous. Use DOM methods instead:

document.getElementById("layer").innerHTML = days.join(", ");

And the HTML as simple as this:

<div id="layer"></div>
Sign up to request clarification or add additional context in comments.

6 Comments

I don't know if this is the correct guess for what the OP is attempting to ask about (question is very unclear), but if so, why don't you put your code into a working snippet?
It's the simplest code that appears in the whole life of stackoverflow hahaha, so if you are exigent, I going to edit with a snippet, don't worry.
Just a suggestion for how to make your answer better. I guess you don't appreciate such suggestions.
@Marcos thank you. So in this case the join() also works as a loop? And yes I know it's not recommended using document.write bla bla bla.. however this is just a test that I am writing.
Yes, join iterates all the array and makes an string with the pattern you define, in this example a comma and an space.
|

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.