用函数推送数组

时间:2013-01-04 22:33:22

标签: javascript

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(标题,评级))来添加我的书籍和一个函数(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();

1 个答案:

答案 0 :(得分: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());

所以你有一个可以优化和处理它的坚固结构。