Javascript - 循环在执行模拟时无法正常工作

时间:2017-04-21 21:25:34

标签: javascript loops prototype nested-loops

我正在尝试使用原型,对象和嵌套循环运行库检入/退出系统的模拟。我无法正确地将伪代码集成到循环本身,并希望得到任何帮助。

//while loop or for loop for 90 days
      //For loop over catalog
         //forloop over patrons 
             //Check if available , if so check book out
             //If not available check book back in
                 //check checking back in check to see if book is overdue and if so add a fine
    //When down loop over patrons to see their fees

循环

for (var i = 0; i < 90; i++) {
        for (var j = 0; j < catalog.length; j++) {
            for (var k = 0; k < patrons.length; i++) {
                var fine = patrons[k].fine;
                if (catalog[k].Available) {
                    catalog[k].checkOut;
                } else {
                    catalog[k].checkIn;
                    patrons[k].read;
                }
                if (catalog[k].isOverdue) {
                    fine = fine + 5.00;
                }
            }
        }
        patrons[i].fine = fine;
    }

所有代码

var Book = function(title, Available, publicationDate, checkoutDate, callNumber, Authors) {
    this.title = title;
    this.Available = Available;
    this.publicationDate = publicationDate;
    this.checkoutDate = checkoutDate;
    this.callNumber = callNumber;
    this.Authors = Authors;
};

var Author = function(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
};

var Patron = function(firstName, lastName, libCardNum, booksOut, fine) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.libCardNum = libCardNum;
    this.booksOut = booksOut;
    this.fine = fine;
};

Book.prototype.checkOut = function() {
    this.Available = false;
    var temp = new Date(1000000000);
    var date = new Date() - temp;
    var res = new Date(date);
    this.checkoutDate = res;
};

Book.prototype.checkIn = function() {
    this.Available = true;
};

Book.prototype.isOverdue = function() {
    var singleDay = 1000 * 60 * 60 * 24;
    var todayDate = new Date().getTime();
    var difference = todayDate - this.checkoutDate.getTime();
    if (Math.round(difference / singleDay) >= 14) {
        return true;
    }
    return false;
};

Patron.prototype.read = function(book) {
    this.booksOut.add(book);
}

Patron.prototype.return = function(book) {
    this.booksOut.remove(this.booksOut.length);
}

var authors = [];
authors[0] = new Author("Auth", "One");
authors[1] = new Author("AutL", "Two");

var catalog = [];
catalog[0] = new Book('Bk1', true, new Date(2001, 1, 21), new Date(), 123456, authors);
catalog[1] = new Book('Bk2', true, new Date(2002, 2, 22), new Date(), 987656, authors);
catalog[2] = new Book('Bk3', true, new Date(2003, 3, 23), new Date(), 092673, authors);
catalog[3] = new Book('Bk4', true, new Date(2004, 4, 24), new Date(), 658342, authors);
catalog[4] = new Book('Bk5', true, new Date(2005, 5, 25), new Date(), 345678, authors);

var patrons = [];
patrons[0] = new Patron('Pat1', 'Wat', 1, catalog, 0.00);
patrons[1] = new Patron('Pat2', 'Wot', 1, catalog, 0.00);
patrons[2] = new Patron('Pat3', 'Wit', 1, catalog, 0.00);
patrons[3] = new Patron('Pat4', 'Wet', 1, catalog, 0.00);
patrons[4] = new Patron('Pat5', 'Wut', 1, catalog, 0.00);

//while loop or for loop for 90 days
      //For loop over catalog
         //forloop over patrons 
             //Check if available , if so check book out
             //If not available check book back in
                 //check checking back in check to see if book is overdue and if so add a fine
    //When down loop over patrons to see their fees

for (var i = 0; i < 90; i++) {
    for (var j = 0; j < catalog.length; j++) {
        for (var k = 0; k < patrons.length; i++) {
            var fine = patrons[k].fine;
            if (catalog[k].Available) {
                catalog[k].checkOut;
            } else {
                catalog[k].checkIn;
                patrons[k].read;
            }
            if (catalog[k].isOverdue) {
                fine = fine + 5.00;
            }
        }
    }
    patrons[i].fine = fine;
}

for (i = 0; i < patrons.length; i++) {
    console.log(patrons[i].firstName + " has checked out the following books:");
    for (j = 0; j < patrons[i].booksOut.length; j++) {
        console.log(patrons[i].booksOut[j].title);
    }
    console.log(patrons[i].firstName + " has fine amount: $" + patrons[i].fine);
}

我正在尝试编写一个模拟结帐和签到3个月的循环。每天我都会遍历目录,以及顾客阵列中的每个人。如果顾客目前已经检查了这本书,那么我将其签入。如果没有签出,那么我将通过顾客阅读方法将其添加到顾客的书籍列表中。如果这本书已经逾期,那么我会向顾客退还5.00美元的罚款。在3个月的结束时,我必须展示每个赞助人,他们目前检查的书籍以及他们可能有的任何罚款。

2 个答案:

答案 0 :(得分:1)

你的循环中有拼写错误(对于var k ... i ++)。请参阅代码段

&#13;
&#13;
var Book = function(title, Available, publicationDate, checkoutDate, callNumber, Authors) {
    this.title = title;
    this.Available = Available;
    this.publicationDate = publicationDate;
    this.checkoutDate = checkoutDate;
    this.callNumber = callNumber;
    this.Authors = Authors;
};

var Author = function(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
};

var Patron = function(firstName, lastName, libCardNum, booksOut, fine) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.libCardNum = libCardNum;
    this.booksOut = booksOut;
    this.fine = fine;
};

Book.prototype.checkOut = function() {
    this.Available = false;
    var temp = new Date(1000000000);
    var date = new Date() - temp;
    var res = new Date(date);
    this.checkoutDate = res;
};

Book.prototype.checkIn = function() {
    this.Available = true;
};

Book.prototype.isOverdue = function() {
    var singleDay = 1000 * 60 * 60 * 24;
    var todayDate = new Date().getTime();
    var difference = todayDate - this.checkoutDate.getTime();
    if (Math.round(difference / singleDay) >= 14) {
        return true;
    }
    return false;
};

Patron.prototype.read = function(book) {
    this.booksOut.add(book);
}

Patron.prototype.return = function(book) {
    this.booksOut.remove(this.booksOut.length);
}

var authors = [];
authors[0] = new Author("Auth", "One");
authors[1] = new Author("AutL", "Two");

var catalog = [];
catalog[0] = new Book('Bk1', true, new Date(2001, 1, 21), new Date(), 123456, authors);
catalog[1] = new Book('Bk2', true, new Date(2002, 2, 22), new Date(), 987656, authors);
catalog[2] = new Book('Bk3', true, new Date(2003, 3, 23), new Date(), 092673, authors);
catalog[3] = new Book('Bk4', true, new Date(2004, 4, 24), new Date(), 658342, authors);
catalog[4] = new Book('Bk5', true, new Date(2005, 5, 25), new Date(), 345678, authors);

var patrons = [];
patrons[0] = new Patron('Pat1', 'Wat', 1, catalog, 0.00);
patrons[1] = new Patron('Pat2', 'Wot', 1, catalog, 0.00);
patrons[2] = new Patron('Pat3', 'Wit', 1, catalog, 0.00);
patrons[3] = new Patron('Pat4', 'Wet', 1, catalog, 0.00);
patrons[4] = new Patron('Pat5', 'Wut', 1, catalog, 0.00);

//while loop or for loop for 90 days
      //For loop over catalog
         //forloop over patrons 
             //Check if available , if so check book out
             //If not available check book back in
                 //check checking back in check to see if book is overdue and if so add a fine
    //When down loop over patrons to see their fees

for (var i = 0; i < 90; i++) {
    for (var j = 0; j < catalog.length; j++) {
        for (var k = 0; k < patrons.length; k++) {
            var fine = patrons[k].fine;
            if (catalog[k].Available) {
                catalog[k].checkOut;
            } else {
                catalog[k].checkIn;
                patrons[k].read;
            }
            if (catalog[k].isOverdue) {
                fine = fine + 5.00;
            }
             patrons[k].fine = fine;
        }
    }
   
}

for (i = 0; i < patrons.length; i++) {
    console.log(patrons[i].firstName + " has checked out the following books:");
    for (j = 0; j < patrons[i].booksOut.length; j++) {
        console.log(patrons[i].booksOut[j].title);
    }
    console.log(patrons[i].firstName + " has fine amount: $" + patrons[i].fine);
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

可能会有所帮助

请记住,他们要求3个月或90天。我们不能只迭代90次。最终你将在同一个月结束。例如:如果今天是2017年10月19日,这意味着该计划应该计算到01/19/2018(3个月期间)

&#13;
&#13;
//***************** library.js *****************//


/**
	Create a constructor function for a Book object. The Book object should have the following properties:
	 
	Title: string 
	Available: Boolean representing whether the book is checked out or not. The initial value should be false. 
	Publication Date: Use a date object
	Checkout Date: Use a date object 
	Call Number: Make one up 
	Authors: Should be an array of Author objects
**/
var Book = function(title, available, publicationDate, checkOutDate, callNumber, authors) {

	this.title = title;
	this.available = available;
	this.publicationDate = publicationDate;
	this.checkOutDate = checkOutDate;
	this.callNumber = callNumber;
	this.authors = authors;
}

/**
	Create a constructor function for an object called Author. It should have a property for the
	 
	first name: string
	last name: string
**/
var Author = function(firstName, lastName) {

	this.firstName = firstName;
	this.lastName = lastName;
}

/**
	Create a constructor function for an object called Patron. This represents a person who is allowed to check out books from the library. Give it the following properties:

	Firstname: string
	Lastname: string
	Library Card Number (Make one up): string
	Books Out (make it an array): []
	fine (Starts a 0.00): parseFloat(0.00)
**/
var Patron = function(firstName, lastName, libraryCardNumber, booksOut, fine) {
	
  this.firstName = firstName;
  this.lastName = lastName;
  this.libraryCardNumber = libraryCardNumber;
  this.booksOut = booksOut;
  this.fine = parseFloat(fine) || 0.00;
}

// Methods
/**
Add a function to the Book prototype called "checkOut". The function will change the available property of the book from true to false and set the checkout date. The checkout date should be set to the current date minus some random number of days between 1 and 5. This will allow us to simulate books being overdue.
**/
Book.prototype.checkOut = function(date) {
  this.available = false;
 
  this.checkOutDate = new Date(date.setDate(date.getDate() - Math.floor((Math.random() * 5) + 1))); 
}

/**
Add a function to the Book prototype called "checkIn". The function will change the available property of the book from false to true.
**/
Book.prototype.checkIn = function() {
  this.available = true;
}

/**
Add a function called isOverdue that checks the current date and the checked out date and if it's greater than 5 days it returns true
**/
Book.prototype.isOverdue = function(date) {
	var time = date.getTime();
	var checkOutDate = (this.checkOutDate).getTime();
	var timeDiff = Math.abs(time - checkOutDate);
	var dayDiff = Math.ceil(timeDiff/ (1000 * 3600 * 24));
  
	if (dayDiff > 5) {
		return true;
	} else {
		return false;
	}
}

/**
Add a function called isCheckedOut that returns true if the book is checked out to someone and false if not.
**/
Book.prototype.isCheckedOut = function() {
	if (this.available === true) {
		return false;
	} else {
		return true;
	}
}

/**
Add a function to the Patron prototype called "read" that adds a book to it's books out property.
**/
Patron.prototype.read = function(book) {
	this.booksOut.push(book);
}

/**
Add a function to the Patron prototype called "return" that removes a book from it's books out property.
**/
Patron.prototype.return = function(book) {
	var booksOut = this.booksOut;
	booksOut.forEach(function(existingBook, index) {
		if (existingBook.title === book.title) {
			booksOut.splice(index, 1);
		}
	});
}

/**
Create 5 different books from the Book Class and store them in an array called catalog.
**/
var catalog = [];

catalog[0] = new Book('Another Brooklyn', false, new Date(2017, 5, 30), new Date(), '201-360-9955', [new Author('Jacqueline', 'Woodson')]);
catalog[1] = new Book('Sunshine State', false, new Date(2017, 4, 11), new Date(), '888-888-888', [new Author('Sarah', 'Gerard')]);
catalog[2] = new Book('Homegoing', false, new Date(2017, 5, 2), new Date(), '877-990-3321', [new Author('Yaa', 'Gyasi')]);
catalog[3] = new Book('Round Midnight', false, new Date(2015, 11, 22), new Date(), '321-221-2100', [new Author('Laura', 'McBride')]);
catalog[4] = new Book('The Sport of Kings', false, new Date('08/22/2016'), new Date(), '813-289-0007', [new Author('C.E.', 'Morgan')]);

/**
Create 5 different patrons from the Patron Class and store them in an array called patrons.
**/
var patrons = [];

patrons[0] = new Patron('Bhaumik', 'Mehta', 'Lib-229781', [catalog[0]], 0.00);
patrons[1] = new Patron('Jeff', 'Reddings', 'Lib-337895', [catalog[1]], 0.00);
patrons[2] = new Patron('Andrew', 'Hansing', 'Lib-227896', [catalog[2]], 0.00);
patrons[3] = new Patron('Dylan', 'Marks', 'Lib-672563', [catalog[3]], 0.00);
patrons[4] = new Patron('Roop', 'Kapur', 'Lib-008936', [catalog[4]], 0.00);


/**
Write a loop that simulates checkouts and checkins for a 3 month period. Every day iterate over each book in the catalog, and every person in the patrons array(Nested Loops). If the current book is not checked out and the current patron does not have a book already, then add it to the patrons list of books via the patrons read method and check it out by calling the books checkout method. If the book is checked out to the current person, then check if it is overdue, and if so, check it in using the books check in method, and return it using the patrons return method. When checking in, if the book is overdue then add a fine of $5.00 to the patron returning it. At the end of the 3 month period, display each patron, the books they have currently checked out and any fine they may have.
**/

var now = new Date();
var threeMonthsFromNow = new Date(now.setMonth(now.getMonth() + 3));
var timeDiff = Math.abs(threeMonthsFromNow.getTime() - new Date().getTime());
var days = Math.ceil(timeDiff/ (1000 * 3600 * 24));

for (var i = 0; i < days; i ++) {

    var date = new Date(new Date().setDate(new Date().getDate() + i));
   
    catalog.forEach(function(item, index) {
  
	    patrons.forEach(function(patron, index) {

		    if (item.isCheckedOut() === false) {
  
			    var booksOut = (patron.booksOut).filter(function(book) {
				    return book.title === item.title;
			    });
   
			    if (booksOut.length === 0) {
    
				    patron.read(item);
				    item.checkOut(date);
			    }
  
		    } else if (item.isCheckedOut() === true) {
  
			    var booksOut = (patron.booksOut).filter(function(book) {
				    return book.title === item.title;
			    });
    
			    if (booksOut.length > 0) {
    
				    var isOverdue = item.isOverdue(date);
  				
				    if (isOverdue === true) {
      
					    item.checkIn();
					    patron.return(item);
					    patron.fine += parseFloat(5.00);
				    }
			    }
		    }
	    });
    });
}

/**
Object with the method to execute the record list for patrons
**/
var records = {
	
	patronInfo: function() {
  
		patrons.forEach(function(patron, index) {

			console.log('Patron name: ' + patron.firstName + ' ' + patron.lastName);
			console.log('Patron library card number: ' + patron.libraryCardNumber);
			console.log('List of book(s) checked out currently by the patron:');

			if ((patron.booksOut).length === 0) {

				console.log('NO BOOKS ARE CHECKED OUT CURRENTLY');

			} else {

				(patron.booksOut).forEach(function(book, index) {

					console.log((index + 1) + '. | ' + book.title + ' | Checked out on: ' + (book.checkOutDate).toDateString());
				});
			}

			console.log('Patron ' + patron.firstName + ' ' + patron.lastName + ' has fine amout(till date): $' + (patron.fine).toFixed(2));
			console.log('-----------------------------------------------------');
		});
	}
};

/**
Method execution
**/
records.patronInfo();
&#13;
&#13;
&#13;