2013-01-04 131 views
0
var books = new Array(); 

books[0] = "Silmarillion: "; 
books[1] = "Horus Rising: "; 
books[2] = "Lord of the Rings: "; 


var ratings = new Array(); 

ratings[0] = "9 "; 
ratings[1] = "8 "; 
ratings[2] = "7 "; 


function printBooks() 
{ 
    for(var i = 0; i < books.length; i++) 
    { 
    document.writeln(books[i] +" " + ratings[i]); 
    } 

} 


printBooks(); 

我有這個代碼,它(基本上)實現了我想要它做的事情,但它是相當糟糕的。我想在兩個函數中添加一個函數(addBooks(title,rating))來添加我的書籍和一個函數(printBooks())來打印它們。我希望用戶被要求添加一本書,詢問它的評級並做三次。 在此之後,我希望它被打印。推功能陣列

我試過這樣做,但我不知道如何編寫添加到數組中的函數。我只知道我應該使用push()而不是更多..我希望它足夠清楚。

編輯

在這上面我也想有一個方法來計算增加的​​書籍的平均得分。我現在得到的代碼是:

function averageRating() 
{ 
var sum = 0; 
for(var u = 0; u < ratings.length; u++) 
{ 
    sum += parseInt(ratings[u]); 
} 
var avg = sum/ratings.length; 
document.writeln("<br>Number of books read: " + ratings.length + "<br>The average rating of the books are: " + avg); 

averageRating(); 

回答

5

這個概念是你有一個圖書館的一些書。 所以一個OOP方法可能會用某種方法創建一個類庫。像:

function Library() { 
    var books = []; 
    this.addBook = function(bookName,rate) { 
     books.push({name:bookName, rating:rate}); 
    } 
    this.printBooks = function() { 
     for(var i = 0; i < books.length; i++) { 
      document.writeln(books[i].name +": " + books[i].rating); 
     } 
    } 
} 

代碼:

var myLibrary = new Library(); 
myLibrary.addBook('Silmarillion',9); 
myLibrary.addBook('Horus Rising',8); 
myLibrary.addBook('Lord of the Rings',7); 

myLibrary.printBooks(); 

但是,它可以改進。您可以創建一個類Book

function Book(name,options) { 
    this.name = name; 
    this.rating = options.rating; 
} 

和類庫變爲:

function Library() { 
    var books = []; 
    this.addBook = function(book) { 
     books.push(book); 
    } 
    this.printBooks = function() { 
     for(var i = 0; i < 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 < books.length; i++) { 
      sum += books[i].rating; 
     } 
     return sum/books.length; 
    } 
} 

和它的使用就變成了:

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("<br>Number of books read: " + myLibrary.countBook() + "<br>The average rating of the books are: " + myLibrary.calculateRatingAverage()); 

所以,你有,你可以優化了堅實的結構,在...上下功夫。

+0

這似乎是做的伎倆..我只是想讓你幫我添加一個函數,寫出書的平均評分以及使其全部完成:) – Benji

+0

創建'書'對象作爲參數對我來說似乎有點不直觀。如果對象是在'addBook'方法內創建的,並且只有數據作爲參數傳遞,那將會更加整潔。 – amustill

+0

@amustill對象如果問題變得更加複雜,那麼Book有意義。所以你有一個對象,你可以隨意複雜。這就是爲什麼它是答案的補充 –