如何从单独对象中的数组中删除对象

时间:2014-04-26 07:00:16

标签: javascript arrays object prototype

我认为这是一个非常标准的测试/家庭作业问题,我无法完成。

它包括创建库,书架和书籍对象。它要求图书馆用书架和书架填充书籍;它还需要有一种方法将书放在书架上并从书架上取下书。

我已经完成了大部分工作,但是有两天我一直在靠墙试图用架子方法从书架上取下一本书。

这是我的代码:

function Library() {
  this.shelves = [];

  //Logs all books in the library
  this.allBooks = function () {
    for (i = 0; i < library.shelves.length; i++) {
        console.log(JSON.stringify(library.shelves[i].books));
    }
  };


}

function Shelf(number) {
  this.number = number;
  this.books = [];

  //This method takes in the shelf number and logs the books on that shelf
  Library.prototype.booksOnShelf = function (shelfNum) {
    var x = shelfNum - 1;

    console.log(JSON.stringify(library.shelves[x].books));
  };
}

function Book(title) {
  this.title = title;

  //Adds a book to a specified shelf
  Library.prototype.enshelf = function (shelfNumber, bookTitle) {
    var y = shelfNumber - 1;
    library.shelves[y].books.push(new Book(bookTitle));
  };

  //this.unshelf = function (shelfNumber, bookTitle) {

  }

var library = new Library();

//Adds shelves to the library
library.shelves.push(new Shelf(1));
library.shelves.push(new Shelf(2));
library.shelves.push(new Shelf(3));

//Adds books to the library
library.shelves[0].books.push(new Book("A Storm of Swords"));
library.shelves[0].books.push(new Book("A Clash of Kings"));
library.shelves[0].books.push(new Book("A Game of Thrones"));
library.shelves[1].books.push(new Book("A Feast for Crows"));
library.shelves[2].books.push(new Book("A Dream of Dragons"));
library.shelves[2].books.push(new Book("Winds of Winter"));
library.shelves[2].books.push(new Book("A Dream of Spring"));




//library.allBooks(); //logs all the books in the library
//library.booksOnShelf(3); // logs all the books on a specified shelf
//console.log(library.shelves.length);//logs # of shelves in library
//library.enshelf(2, "Harry Potter");
//library.booksOnShelf(2);
library.allBooks();
//.unshelf("A Storm of Swords"); //Haven't figured this out yet
//library.allBooks();

到目前为止,除了unshelf方法之外,一切都有效,我尝试了很多不同的方法。

如果有人能让我走上正确的道路,我将不胜感激。我一直在考虑的是将方法放在不同的对象中。另外,我不使用任何'返回',这可能会有所帮助?当我尝试调用library.shelves [arg] .books.splice(arg,arg)时,控制台告诉我我不能这样做。

总之,请帮我把一本特定的书从书架上拿下来。

0 个答案:

没有答案