有人能解释一下如何正确编写这个Javascript程序吗?

4
我希望有人能够向我展示如何完成此任务以及我哪里出错了。以下是说明:
“请在此长注释下方的文件中编写您的练习代码。请确保仅使用所分配的FreeCodeCamp课程中涵盖的语法和技术。”
(这里提到的材料是FreeCodeCamp基本JavaScript的110个课程,探索Var和Let关键字以及26个面向对象编程课程)
  1. 编写一个名为createMovie的函数,该函数期望接收三个参数:title、duration和quote。此函数应返回一个对象。返回的对象也应具有名为title、duration和quote的属性。分配给这些属性的值应该是传递给函数的值。此外,createMovie返回的对象应具有两个方法:

    isLongerThan - 一个函数,它接受一个电影对象作为参数,并返回true,如果电影比作为参数传递给它的电影长,并返回false否则。

    logQuote - 一个函数,将电影对象的quote属性的值记录到控制台中。

  2. 创建一个名为movies的变量并将其分配给一个数组。该数组应包含六个对象,这些对象通过调用createMovie函数创建。您应该传递给createMovie函数以创建这些对象的值是:

title              | duration | line
----------------------------------------------------------------------------
Star Wars          |   121    | If there's a bright center to the universe,
                   |          | you're on the planet that it's farthest from.
                   |          |
Pulp Fiction       |   154    | Do you know what they call a Quarter Pounder
                   |          | with Cheese in France?
                   |          |
Dirty Dancing      |   100    | Nobody puts Baby in a corner.
                   |          |
Forrest Gump       |   142    | Life is like a box of chocolates.
                   |          |
The Wizard of Oz   |   101    | Lions and tigers and bears, oh my!
                   |          |
Cabaret            |   124    | Life is a cabaret, old chum, so come to the
                   |          | cabaret.

请编写以下两个函数,它们都使用电影数组来确定返回什么。
getMovieByTitle - 这个函数期望一个字符串作为参数,并返回在电影数组中其标题属性等于传递给它的字符串的对象(如果有的话)。
getAverageDuration - 这个函数返回数组中所有电影的平均持续时间。
您可以通过在Chrome中打开index.html并使用控制台来测试代码(请参见http://jsforcats.com/以获取有关使用控制台的说明)。在纠正打开控制台时看到的任何错误后,您可以运行像下面这样的命令并验证输出。
var starWars = getMovieByTitle('星球大战');
var pulpFiction = getMovieByTitle('低俗小说');

pulpFiction.isLongerThan(starWars);

pulpFiction.logQuote();

getAverageDuration();

所以我编写的代码是根据一些伪代码形成的,这是我能够接近答案的最佳方式。 我完全是新手,肯定咬了更多的东西。任何帮助都将不胜感激。 以下是我到目前为止的进展:

var Movies = [];

function CreateMovie (id, title, duration, quote) {

  let Films = {
    title: title,
    duration: duration,
    quote: quote,
    isLongerThan: function (Movies) {
      for (var x = 0; x < Movies.length; x++) {
        for (var y = 0; y < Movies[x].length; y++) {
      if (This.duration > Movies[x][y].duration) {
        return true;
      } else {
        return false;
            }
          }
        }
      },
    logQuote: function (title){
      for (var x = 0; x < Movies.length; x++) {
        for (var y = 0; y < Movies[x].length; y++){
      if (Movies[x][y].hasOwnProperty(title)){
        console.log(Movies[x][y].quote)
          }
        }
      }
    }
  };

  Movies.push(Films);

  return Films;
};

function getMovieByTitle (title) {
  for (var x = 0; x < Movies.length; x++) {
    for (var y = 0; y < Movies[x].length; y++) {
  if (title === Movies[x][y].title) {
    return Movies[x];
  } else {
    return undefined;
  }
};

function getAverageDuration () {
  var totalMovies = [];
  for (var i = 0; i < Movies.length; i++) {
  totalMovies.push[i];
}
  var durationTotal = 0;
  for (var x = 0; x < Movies.length; x++) {
      durationTotal += (Movies[x][2]) ;
    }

  var totalAvg = (durationTotal / totalMovies.length);
  return totalAvg;
};

我知道这些可能都是完全无用的代码,但我希望如果有人能为我指点迷津,那么它可能会激励我继续学习编程,而不是放弃并永远在酒吧工作。


1
嘿,欢迎来到StackOverflow,我可以在几个小时后看一下! 我想我知道为什么,但需要确认一下! - Mrk Fldig
欢迎来到编程的世界。让我看看能否用原生JavaScript编写出一些东西。 - Kalesh Kaladharan
请务必仅使用在指定的freeCodeCamp课程中涵盖的语法和技术。由于此限制,回答此问题可能会很困难。 - Andy
4个回答

3

很遗憾听到你的挫折。这是代码,请让我知道如果你有问题:

class Movie {
    constructor(title, duration, quote) {
        this.title = title;
        this.duration = duration;
        this.quote = quote;
    }

    isLongerThan(other) {
        return this.duration > other.duration;
    }

    logQuote() {
        console.log(this.quote);
    }
}

function createMovie(title, duration, quote) {
    return new Movie(title, duration, quote);
}

function getMovieByTitle(movies, title) {
    for (let m of movies)
        if (m.title === title)
            return m;
}

function getAverageDuration(movies) {
    let total = 0;

    for (let m of movies)
        total += m.duration;

    return total / movies.length;
}

3

这是最简单的版本,没有使用任何类和你还未熟悉的函数。我用循环写了一个简单的解决方案。你可以按照其他答案中给出的那样,使用 classmap 函数编写相同的代码。

let movies = [];

/**
 * Creates a new movie object and adds the object to
 * the movies array.
 * 
 * Returns the newly created movies object.
 */
function createMovie(title, duration, quote) {

    let movie = {
        title: title,
        duration: duration,
        quote: quote,
        isLongerThan: function (other_movie) {            
            return this.duration > other_movie.duration;
        },
        logQuote: function () {
            console.log(this.quote);
        }
    }
    movies.push(movie);

    return movie;
}

/**
 * Searches the movies array for matching title and returns 
 * the movie object if a match is found. Returns "undefined"
 * if no atch is found.
 * 
 * @param string title 
 */
function getMovieByTitle(title) {
    for (let i = 0; i < movies.length; i++) {
        let movie = movies[i];

        if (movie.title === title) {
            return movie;
        }
    }
}

/**
 * Gets the average duration of all the movies using a simple
 * for loop.
 */
function getAverageDuration() {

    let total_duration = 0;
    let average_duration = 0;

    if (movies.length > 0) {
        // Iterate through the movies, if movies array
        // is not empty. If we don't do this check, the average
        // duration could result in an NaN result (division by 0).
        for (let i = 0; i < movies.length; i++) {
            let movie = movies[i];

            total_duration += isNan(movie.duration) ? 0 : movie.duration;
        }
        // Rounds the average to two decimal places.
        average_duration = (total_duration / movies.length).toFixed(2);
    }
    return average_duration;
}

0

花钱学习却没有得到认可真是太糟糕了 :/。希望你不要放弃!我试图复制你的环境,但在你的任务中规定了不能使用未学过的其他东西。我使用了比你更现代的for循环...

var movies = [];

// Task 1:
function createMovie(title, duration, quote) {
    // Something missing
    if (!title || !duration || !quote) {
        console.error('Missing parameter.');

        return null;
    }
    // Convert type
    if (typeof duration === 'string') {
        duration = Number(duration);
    }
    // Check type
    if (typeof title !== 'string' || typeof duration !== 'number' || typeof quote !== 'string') {
        console.error('Parameter type incorrect.');

        return null;
    }

    return {
        title,
        duration,
        quote,
        methods: {
            isLongerThan: (movie) => {
                if (movie && typeof movie === 'object' && duration > movie.duration) { return true; }
                return false;
            },
            logQuote: () => {
                console.log('Quote:', quote);
            }
        }
    };
}

// Task 2: Add movies
movies.push(createMovie('Star Wars', 121, 'If there\'s a bright center to the universe, you\'re on the planet that it\'s farthest from.'));
movies.push(createMovie('Pulp Fiction', 154, 'Do you know what they call a Quarter Pounder with Cheese in France?'));
movies.push(createMovie('Dirty Dancing', 100, 'Nobody puts Baby in a corner.'));
movies.push(createMovie('Forrest Gump', 142, 'Life is like a box of chocolates.'));
movies.push(createMovie('The Wizard of Oz', 101, 'Lions and tigers and bears, oh my!'));
movies.push(createMovie('Cabaret', 124, 'Life is a cabaret, old chum, so come to the cabaret.'));

// Task 3:
function getMovieByTitle(title) {
    // Should maybe be async
    if (title && typeof title === 'string') {
        for (let movie of movies) {
            if (movie.title.toLocaleLowerCase() === title.toLocaleLowerCase()) {
                return movie;
            }
        }
    }

    return null;
}
function getAverageDuration() {
    // Should maybe be async
    let combinedDurations = 0;

    for (let movie of movies) {
        combinedDurations += movie.duration;
    }

    return (combinedDurations / movies.length);
}

//
// Display some results
var movie0 = document.getElementById('movie0');
var movie0Compared = document.getElementById('movie0-compared');

movie0.innerHTML = '<pre>' + JSON.stringify(movies[0], undefined, 2) + '</pre>';
movie0Compared.innerHTML = 'Is Movie 0 longer than Movie 1? <b>' + movies[0].methods.isLongerThan(movies[1]) + '</b>';

movies[0].methods.logQuote();
console.log('Pulp Fiction:', getMovieByTitle('pulp fiction').duration, 'min');
console.log('Average duration:', getAverageDuration().toFixed(0), 'min');
<h1>Results for: Movie0</h1>

<div id="movie0"></div>
<div id="movie0-compared"></div>

<br>
<br>
<br>
<br>
<br>


0

卡在一段代码上真是太糟糕了。我们都曾经历过这种情况。
以下是我如何执行您的任务。

就像@georg一样,如果您有任何问题,请告诉我们。

class Movie {

    constructor(title, duration, quote) {
        this.title = title;
        this.duration = duration;
        this.quote = quote;
    }

    isLongerThan(movie) {
        return this.movie.duration > movie.duration;
    }

    logQuote() {
        console.log(this.quote);
    }

}

const movies = [];

function createMovie(title, duration, quote) {
    let movie = new Movie(title, duration, quote);
    movies.push(movie);
}

function getMovieByTitle(title) {
    return movies.find(movie => movie.title === title);
}

function getAverageDuration() {
    return movies.reduce(accumulator, movie => {
        return accumulator + movie.duration;
    }, 0) / movies.length;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接