我是javascript的初学者,因此感谢您提供的任何帮助/建议。

我在这里的问题是,我试图弄清楚如何在times []数组的项目之间添加空间,该数组保存每个电影对象的放映时间值。我试图用逗号(“,”)分割,但这不起作用。当我尝试在(“pm”)拆分时,该方法起作用了。我还想出了一种在放映时间值本身中增加空间的方法,但我认为必须有更好的方法来解决这个问题。有什么想法吗?谢谢!

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


 }

最佳答案

array.join函数采用可选的delimiter参数,该参数将通过定界符分隔元素。一个简单的例子:

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

09-26 22:29