图书借阅(对象数组+构造)
时间: 2023-05-23 14:05:39 浏览: 85
A:为了方便图书馆管理,我们可以使用对象数组来构造图书借阅系统。首先需要定义一个Book类,表示一本书的属性和行为,如书名、作者、出版社、ISBN号等,并且可以实现借出和归还两个方法。然后定义一个Borrower类,表示借书人的属性和行为,如姓名、电话、借阅的书籍等,并且可以实现借书和还书两个方法。
接下来定义一个Library类,表示图书馆的属性和行为,如存储所有书籍的数组books,存储所有借阅人的数组borrowers,以及借阅和归还书籍的方法。在借阅书籍时,需要检查该书籍是否存在且未被借出,若满足条件则将其标记为已被借出,并将借阅人的信息添加到borrowers数组中;在归还书籍时,需要检查该书籍是否存在且已被借出,若满足条件则将其标记为未被借出,并将该借阅人的信息从borrowers数组中移除。
示例代码:
class Book {
constructor(name, author, publisher, isbn) {
this.name = name;
this.author = author;
this.publisher = publisher;
this.isbn = isbn;
this.borrowed = false;
}
borrow() {
this.borrowed = true;
}
return() {
this.borrowed = false;
}
}
class Borrower {
constructor(name, phone) {
this.name = name;
this.phone = phone;
this.books = [];
}
borrow(book) {
this.books.push(book);
}
return(book) {
const index = this.books.indexOf(book);
if (index !== -1) {
this.books.splice(index, 1);
}
}
}
class Library {
constructor() {
this.books = [];
this.borrowers = [];
}
addBook(book) {
this.books.push(book);
}
removeBook(book) {
const index = this.books.indexOf(book);
if (index !== -1) {
this.books.splice(index, 1);
}
}
borrowBook(book, borrower) {
if (book && !book.borrowed) {
book.borrow();
borrower.borrow(book);
this.borrowers.push(borrower);
}
}
returnBook(book, borrower) {
if (book && book.borrowed) {
book.return();
borrower.return(book);
const index = this.borrowers.indexOf(borrower);
if (index !== -1) {
this.borrowers.splice(index, 1);
}
}
}
}
// 创建几本图书和几位借阅人
const book1 = new Book("JavaScript高级程序设计", "Nicholas C. Zakas", "人民邮电出版社", "9787115422358");
const book2 = new Book("CSS揭秘", "Lea Verou", "人民邮电出版社", "9787115378693");
const book3 = new Book("HTML5与CSS3基础教程", "南京审计大学出版社", "南京审计大学出版社", "9787304108356");
const borrower1 = new Borrower("张三", "13888888888");
const borrower2 = new Borrower("李四", "13999999999");
// 创建图书馆
const library = new Library();
library.addBook(book1);
library.addBook(book2);
library.addBook(book3);
// 张三借书
library.borrowBook(book1, borrower1);
console.log(`张三借了一本书《${book1.name}》。`);
console.log(`借阅人数:${library.borrowers.length},在借书籍数:${library.books.filter(book => book.borrowed).length}`);
// 李四借书
library.borrowBook(book2, borrower2);
console.log(`李四借了一本书《${book2.name}》。`);
console.log(`借阅人数:${library.borrowers.length},在借书籍数:${library.books.filter(book => book.borrowed).length}`);
// 张三还书
library.returnBook(book1, borrower1);
console.log(`张三还了一本书《${book1.name}》。`);
console.log(`借阅人数:${library.borrowers.length},在借书籍数:${library.books.filter(book => book.borrowed).length}`);
// 李四还书
library.returnBook(book2, borrower2);
console.log(`李四还了一本书《${book2.name}》。`);
console.log(`借阅人数:${library.borrowers.length},在借书籍数:${library.books.filter(book => book.borrowed).length}`);