【问题标题】:Can someone explain how to properly write this Javascript program?有人可以解释如何正确编写这个 Javascript 程序吗?
【发布时间】:2019-11-03 13:17:35
【问题描述】:

我正在找人指导我应该如何完成这项任务以及我哪里出错了。说明如下:

“在这个长注释下面的这个文件中写下你的练习代码。 请务必仅使用指定的语法和技术 免费CodeCamp 课程。

(这里引用的资料是FreeCodeCamp的110节Javascript基础课,探索Var和Let关键字以及26节面向对象编程课)

  1. 编写一个名为 createMovie 的函数,该函数期望接收三个参数: 标题、持续时间和报价。这个函数应该返回一个对象。物体 它返回的属性应该也被命名为 title、duration 和 引用。分配给这些属性的值应该是 传递给函数。此外,createMovie 返回的对象 应该有两种方法:

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

    logQuote - 记录电影对象引用值的函数 属性到控制台。

  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.
  1. 编写以下两个函数,这两个函数都使用movies数组来 确定要返回的内容。

    getMovieByTitle - 此函数需要一个字符串作为参数,并且 返回电影数组中 title 属性等于的对象 传递给它的字符串(如果有的话)。

    getAverageDuration - 这个函数返回所有的平均持续时间 数组中的电影。

您可以通过在 Chrome 中打开 index.html 并使用控制台来测试您的代码 (有关使用控制台的说明,请参阅http://jsforcats.com/)。在你之后 更正您在打开控制台时看到的任何错误,您可以运行以下命令 如下所示并验证输出。

var starWars = getMovieByTitle('星球大战');

var pinchFiction = getMovieByTitle('Pulp Fiction');

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;
};

我很欣赏这可能完全是垃圾代码,但我希望如果有人可以向我展示光明,它可能会激励我继续编码而不是放弃并永远继续在酒吧工作

【问题讨论】:

  • 欢迎来到 StackOverflow,我可以在几个小时内看看!我想我可以看到原因,但需要检查!
  • 欢迎来到编程世界。让我看看我能不能用 Vanilla Javascript 想出一些东西。
  • “请务必只使用指定的 freeCodeCamp 课程中涵盖的语法和技术。”:由于这个限制,这个问题将很难回答。

标签: javascript


【解决方案1】:

很遗憾听到您的挫折。这是代码,如果您有任何问题,请告诉我:

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;
}

【讨论】:

    【解决方案2】:

    这是最简单的版本,不使用任何类和您尚未熟悉的功能。我用循环编写了一个简单的解决方案。您可以使用其他答案中给出的 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;
    }
    

    【讨论】:

      【解决方案3】:

      卡在一段代码上很糟糕。我们都去过那里。
      这就是我执行你的任务的方式。

      就像@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;
      }
      

      【讨论】:

        【解决方案4】:

        它会花钱在教育上而没有得到批准:/。希望你不要放弃! 我试图复制你的环境。它代表你的任务,你不应该使用你还没有学过的其他东西。我使用了比你更现代的 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>

        【讨论】:

          猜你喜欢
          • 2011-01-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多