使用push()
方法后,我将项目arr[i].title
打印到控制台中,它显示“未定义”,而不是"上帝父亲1"。见代码第12行。
以下是代码:
<!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>
答案 0 :(得分:2)
您没有在对象构造函数中创建任何属性,只是用值覆盖参数。
您想获取参数并输入属性:
function Movie(title,year,genre,rating,showtimes) {
this.title = title;
this.year = year;
this.genre = genre;
this.rating = rating;
this.showtimes = showtimes;
}
答案 1 :(得分:1)
您在var
内使用Movie
创建变量,但这不是您向对象添加属性的方式。您必须将值分配给this
。
function Movie(title, year, genre, rating, showtimes) {
this.title = title;
this.year = year;
// etc
}