Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The concept is you have a library with some books. So an OOP approach may be create a class Library with some method. Like:</p> <pre><code>function Library() { var books = []; this.addBook = function(bookName,rate) { books.push({name:bookName, rating:rate}); } this.printBooks = function() { for(var i = 0; i &lt; books.length; i++) { document.writeln(books[i].name +": " + books[i].rating); } } } </code></pre> <p>code:</p> <pre><code>var myLibrary = new Library(); myLibrary.addBook('Silmarillion',9); myLibrary.addBook('Horus Rising',8); myLibrary.addBook('Lord of the Rings',7); myLibrary.printBooks(); </code></pre> <p><strong>However, it can be improved.</strong> You can create a class <code>Book</code>:</p> <pre><code>function Book(name,options) { this.name = name; this.rating = options.rating; } </code></pre> <p>and class Library becomes:</p> <pre><code>function Library() { var books = []; this.addBook = function(book) { books.push(book); } this.printBooks = function() { for(var i = 0; i &lt; books.length; i++) { document.writeln(books[i].name +": " + books[i].rating); } } // EDIT: ADDED for new features required this.countBook = function() { return books.length; } this.calculateRatingAverage = function() { var sum = 0; for(var i = 0; i &lt; books.length; i++) { sum += books[i].rating; } return sum/books.length; } } </code></pre> <p>and its use becomes:</p> <pre><code>var myLibrary = new Library(); myLibrary.addBook(new Book('Silmarillion',{rating:9})); myLibrary.addBook(new Book('Horus Rising',{rating:8})); myLibrary.addBook(new Book('Lord of the Rings',{rating:7})); myLibrary.printBooks(); document.writeln("&lt;br&gt;Number of books read: " + myLibrary.countBook() + "&lt;br&gt;The average rating of the books are: " + myLibrary.calculateRatingAverage()); </code></pre> <p>So you have a solid structure that you can optimize and work on it.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload