Reputation:
I've been reading a book for beginners, "First-Head HTML5 Programming" and there is this piece of code:
var movie2 = {
title: "Forbidden Planet",
genre: "Classic Sci-fi",
rating: 5,
showtimes: ["5:00pm", "9:00pm"]
};
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();
}
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;
}
Currently, if i call getNextShowing(movie2)
it returns that next showing is at 5:00 PM.
I changed the loops condition to "i <= movie.showtimes.length;" but it still runs only once and shows only 5:00 PM.
Loop iterates only once even if i rewrite this function:
function getNextShowing(movie) {
var now = new Date().getTime();
for (var i = 0; i <= movie.showtimes.length; i++) {
var showtime = getTimeFromString(movie.showtimes[i]);
return "Next showing of" + movie.title + " is " + movie.showtimes[i];
}
return null;
}
Am i not getting something here?
At the first iteration i=0, loops runs and shows item of showtimes
at index 0. After that it's i=1 and it should show item on index 1, no?
Shouldn't it run twice?
Upvotes: 0
Views: 243
Reputation: 1296
You must have to know the detail of return keyword.
You can see this link for more detail. Thank you.
Upvotes: 2
Reputation:
If any poor idiot like me suffers from this "problem" - it's all because return
ends the function execution. Jeeze..
Upvotes: 1