31

I am a beginner at javascript so I appreciate any help/advice given.

My issue here is that I'm trying to figure out how to add space between items in the times[] array which holds the values for showtimes for each movie object. I tried to split at the comma (",") but that isn't working. When I tried splitting at ("pm") that worked. I also figured out a way to add space in the showtimes values themselves, but I thought that there must be a better way to go about it. Any thoughts? thanks!

window.onload = init;
function Movie(title, year, showtimes) { 
 this.title = title;
 this.year = year;
 this.showtimes = showtimes;
 }
 function init() {
 var darkKnight = new Movie("The Dark Knight Rises", "2012", ["1pm,", "2pm,", "3pm,"]);
 var takeThisWaltz = new Movie ("Take This Waltz", "2012", ["4pm", "5pm","6pm"]);
 var watchmen = new Movie("Watchmen", "2009", ["7pm","8pm","9pm"]); 
 var movieList = [darkKnight, takeThisWaltz, watchmen]
 for(var i = 0; i < movieList.length; i++) { 
 var theObj = movieList[i];
 var times = [movieList[i].showtimes] 
 for(var j = 0; j < times.length; j++) {
 var str = times[i]; 
 } 
 makeResult(); }
 function makeResult() { 
 var list = document.getElementById("movieList"); 
 var li = document.createElement("li"); 
 li.innerHTML = "title: " + movieList[i].title + " year: " + movieList[i].year + " showtimes: " + times[0].toString().split(",");
 list.appendChild(li); }
 }
asked Dec 18, 2012 at 18:54

2 Answers 2

88

the array.join function takes an optional delimiter parameter which will seperate the elements by the delimiter. A simple example:

var showtimes = ["1pm", "2pm", "3pm"];
var showtimesAsString = showtimes.join(', '); // gives "1pm, 2pm, 3pm"
Halogen
5416 silver badges11 bronze badges
answered Dec 18, 2012 at 18:58
Sign up to request clarification or add additional context in comments.

1 Comment

I made the mistake of saving my joined array into another array instead of a string, which didn't fail but output unwanted commas.
-1

const names = ["alice", "bob", "charlie", "danielle"]
 
 
 const capitalized = names.map((name) => {
 return name[0].toUpperCase() + name.slice(1)
 })
 
 console.log(capitalized)

["Alice", "Bob", "Charlie", "Danielle"]
answered Sep 12, 2022 at 17:53

1 Comment

the question was about spaces, not capitalization. are you sure you replied to the right question?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.