Logo
Section 1 / 15

上下文:一部电影列表

让我们深入了解一种称为重构的新功能。

导入

上下文:一部电影列表

让我们深入了解一种称为重构的新功能。

在本节中,我们将从一个示例程序开始,逐步对其进行改进,但不添加任何新的功能。这一重要的编程任务被称为 重构。

我们最初的程序涉及最近的蝙蝠侠系列电影。数据以对象数组的形式呈现,每个对象描述了一部电影。

1const movieList = [ 2 { 3 title: "Batman", 4 year: 1989, 5 director: "Tim Burton", 6 imdbRating: 7.6 7 }, 8 { 9 title: "Batman Returns", 10 year: 1992, 11 director: "Tim Burton", 12 imdbRating: 7.0 13 }, 14 { 15 title: "Batman Forever", 16 year: 1995, 17 director: "Joel Schumacher", 18 imdbRating: 5.4 19 }, 20 { 21 title: "Batman & Robin", 22 year: 1997, 23 director: "Joel Schumacher", 24 imdbRating: 3.7 25 }, 26 { 27 title: "Batman Begins", 28 year: 2005, 29 director: "Christopher Nolan", 30 imdbRating: 8.3 31 }, 32 { 33 title: "The Dark Knight", 34 year: 2008, 35 director: "Christopher Nolan", 36 imdbRating: 9.0 37 }, 38 { 39 title: "The Dark Knight Rises", 40 year: 2012, 41 director: "Christopher Nolan", 42 imdbRating: 8.5 43 } 44];

以下是使用这些数据展示电影相关信息的完整程序。

1// 获取电影标题 2const titles = []; 3for (const movie of movieList) { 4 titles.push(movie.title); 5} 6console.log(titles); 7 8// 统计克里斯托弗·诺兰执导的电影数量 9const nolanMovieList = []; 10for (const movie of movieList) { 11 if (movie.director === "Christopher Nolan") { 12 nolanMovieList.push(movie); 13 } 14} 15console.log('列表中有 ' + nolanMovieList.length + ' 部克里斯托弗·诺兰执导的电影。'); 16 17// 获取IMDB评分大于等于7.5的电影标题 18const bestTitles = []; 19for (const movie of movieList) { 20 if (movie.imdbRating >= 7.5) { 21 bestTitles.push(movie.title); 22 } 23} 24console.log(bestTitles); 25 26// 计算克里斯托弗·诺兰电影的平均评分 27let ratingSum = 0; 28let averageRating = 0; 29for (const movie of nolanMovieList) { 30 ratingSum += movie.imdbRating; 31} 32averageRating = ratingSum / nolanMovieList.length; 33console.log(averageRating);

理解面向对象编程

程序状态