0

After using push() method, I print the item arr[i].title into console and it shows 'undefined', instead of "God father 1". See line 12 of the code.

Here is the code:

<!doctype html>
<html lang="en">
<head>
    <title> Document Object Properties </title>
    <meta charset="utf-8">
    <script>
        window.onload = init;
        function init() {
            var arr = [];
            for (var i=0; i < 3; i++) {
                arr.push(new Movie("God father " + i,1970,"Cowboy",15,["13:00","17:00","21:00"]));
                console.log("Array item: " + arr[i].title); // WHY Undefined???
                for (var j=0; j < 3; j++) {
                    //arr[i].showtimes[j] = "0" + i + ":00";
                }
            }
            var div = document.getElementById("result");
            div.innerHTML = 
                "Movie: " + arr[0].title + "<br>" +
                "Year: " + arr[0].year + "<br>" +
                "Genre: " + arr[0].genre;
        }

        function Movie(title,year,genre,rating,showtimes) {
            var title= " ";
            var year= 2000;
            var genre= " ";
            var rating= 15;
            var showtimes= [];
        }
    </script>
</head>
<body>
    <div id="result">
    </div>       
</body>
</html>
JJJ
  • 32,902
  • 20
  • 89
  • 102
Hesham
  • 525
  • 1
  • 5
  • 11

2 Answers2

2

You are not creating any properties in the object constructor, you are just overwriting the parameters with values.

You want to take the parameters and put in properties:

function Movie(title,year,genre,rating,showtimes) {
  this.title = title;
  this.year = year;
  this.genre = genre;
  this.rating = rating;
  this.showtimes = showtimes;
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

You're creating variables with var inside Movie, but that's not how you add properties to objects. You have to assign the values to this.

function Movie(title, year, genre, rating, showtimes) {
    this.title = title;
    this.year = year;
    // etc
}
Eevee
  • 47,412
  • 11
  • 95
  • 127