实现的功能:
图书管理->查找 添加 删除 修改
代码实现:
// 1.提供少量数组,数组中存放少量书var books = [ {name : '三国演义',author : '罗贯中'}, {name : '水浒传',author : '施耐庵'}, {name : '西游记',author : '吴承恩'}, {name : '红楼梦',author : '曹雪芹'}]// 2.查找for (var i = 0; i < books.length; i++) { var obj = books[i]; // 判断 if(obj.name == '三国演义'){ console.log(obj); }}// 3.增加books.push({name:'悟空传',author : '今何在'});console.log(books);// 4.修改for (var i = 0; i < books.length; i++) { var obj = books[i]; if(obj.name == '红楼梦'){ obj.author = '曹操'; }}console.log(books);// 5.删除for (var i = 0; i < books.length; i++) { var obj = books[i]; if(obj.name == '西游记'){ // splice:从index位置开始删除几个元素 books.splice(i,1); }}console.log(books);
函数封装:
// 1.提供一个构造函数function BookManger(books) { // this = obj;// this.books = null; this._init(books);}// 2.设置原型对象BookManger.prototype = { constructor : BookManger, // 提供一个初始化的方法 _init : function (books) { this.books = books || []; }, getBookByName : function (name) { for (var i = 0; i < this.books.length; i++) { var obj = this.books[i]; // 判断 if(obj.name == name){ return obj; } } throw 'Sorry!没有找到这本书!';}, addBook : function (book) { this.books.push(book);}, updateBookByName : function (name,author) { // 1.查找 (在原型方法中调用原型方法要用 this) var book = this.getBookByName(name); // 2.修改 book.author = author;}, deleteBook : function (name) { // 1.查找到这本书 var book = this.getBookByName(name); // 2.获取这本书的索引 var index = this.books.indexOf(book); // 3.删除 this.books.splice(index,1);}}