const app=new Vue({ el:'#app', data:{ books:[{ id:1, name:"算法导论", data: '2006-1', price:39.00, count:1 },{ id:2, name:"算法导论", data: '2006-1', price:39.00, count:1 },{ id:3, name:"算法导论", data: '2006-1', price:39.00, count:1 },{ id:4, name:"算法导论", data: '2006-1', price:39.00, count:1 }] }, methods:{ getfinalprice(price){ return "$"+price.toFixed(2); }, decreasement(index){ this.books[index].count--; }, increasment(index){ this.books[index].count++; }, remove(index){ this.books.splice(index,1); } }, filters:{ getp(price){ return "$"+price.toFixed(2); } }, computed:{ totalPrice(){ // let result=0; //1普通for循环 // for (let i=0;i<this.books.length;i++){ // result+=this.books[i].price*this.books[i].count; // } // return result; // 2for(let i in this.books) // for (let i in this.books){ // console.log(i);//可以获得下标的索引值 // } // 3直接拿到books的每一项 // let totalprice=0; // for (let item of this.books){ // totalprice+=item.price*item.count; // } // return totalprice; // 4高阶函数 /* * filter map reduce * filter中的回调函数有一个要求,必须返回一个布尔值;符合条件则会打印在一个新的数组中 * true:函数内部会自动将这次回调的n加入到新的数组中 * false:当返回false时,函数内部就会过滤掉这次的n * * */ // const nums=[122,2,3,43,53,6,7,8,]; // let newnum= nums.filter(function (n) { // return n<100; // }); // console.log(newnum) // //map函数的使用 特点直接进行计算; // let new2=nums.map(function (n) { // return n*2; // }); // console.log(new2); // reduce函数的使用 作用:对数组中的所有内容进行汇总; // const nums=[122,2,3,43,53,6,7,8]; // let num3=nums.reduce(function (prevalue,n){ // return prevalue +n; // },0); // return num3; // 使用高阶函数进行实现 // const nums=[122,2,3,43,53,6,7,8]; // let total=nums.filter(function (n) { // return n<100; // }).map(function (n) { // return n*2; // }).reduce(function (prevalue,n) { // return prevalue+n; // },0); // console.log(total); return this.books.reduce(function (prevalue,book) { return prevalue+book.price*book.count ; },0) }}});
来源:https://www.cnblogs.com/Damocless/p/11911947.html