2012-12-18 7 views
9

Sono un principiante su javascript quindi apprezzo qualsiasi aiuto/consiglio dato.come aggiungere spazi tra gli elementi dell'array javascript

Il mio problema qui è che sto cercando di capire come aggiungere spazio tra gli elementi nella matrice times [] che contiene i valori per gli orari di programmazione per ciascun oggetto filmato. Ho provato a dividere la virgola (",") ma non funziona. Quando ho provato a dividere ("pm") ha funzionato. Ho anche trovato un modo per aggiungere spazio agli stessi valori degli orari degli spettacoli, ma ho pensato che ci fosse un modo migliore per farlo. qualche idea? Grazie!

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); } 


} 

risposta

34

la funzione array.join prende un delimiter parametro facoltativo che separare gli elementi con il delimitatore. Un semplice esempio:

var showtimes = ["1pm", "2pm", "3pm"]; 
var showtimesAsString = showtimes.join(', '); // gives "1pm, 2pm, 3pm" 
+1

Ho commesso l'errore di salvare il mio array unito in un altro array invece di una stringa, che non ha avuto esito negativo ma ha generato virgole indesiderate. –

Problemi correlati