2011-11-20 116 views
0

请看这段代码,告诉我为什么不起作用?我认为功能回报存在问题。感谢所有的回放。从函数返回值的问题

var movie1 = { 
    title: "Buckaroo Banzai", 
    genre: "Cult classic", 
    rating: 5, 
    showtimes: ["1:00pm", "3:00pm", "7:00pm"] 
} 

function getNextShowing(movie) { 
    var now = new Date().getTime(); 
    for (var i = 0; i < movie.showtimes.length; i++) { 
     var showtime = getTimeFromString(movie.showtimes[i]); 
     if ((showtime - now) > 0) { 
      return "Next showing of " + movie.title + " is " + movie.showtimes[i]; 
     } 
    } 
    return null; 
} 

function getTimeFromString(timeString) { 
    var theTime = new Date(); 
    var time = timeString.match(/(\d+)(?::(\d\d))?\s*(p?)/); 
    theTime.setHours(parseInt(time[1]) + (time[3] ? 12 : 0)); 
    theTime.setMinutes(parseInt(time[2]) || 0); 
    return theTime.getTime(); 
} 

var nextShowing = getNextShowing(movie1); 
alert(nextShowing); 

回答

1

的问题是与这行代码:

if ((showtime - now) > 0) 

(showtime - now)总是小于零因此getNextShowing()函数总是返回null;

+0

感谢您的重播 – user1033392

+2

@ user1033392 :)说感谢是不够的。您必须投票回答此问题,并考虑将其标记为您接受的答案,如果这能解决您的问题。 – Lion

0

我测试了上面的代码,当我的电脑中的时间大于或等于下午7:00时,它只返回了一个null。

否则它工作正常。尝试更改放映时间阵列的时间,以使它们在计算机中的当前时间之前。或者在早上尝试运行它:)。 我认为这就是你需要做的。