只是把之前的知识又复习一遍。

<body>
    <div id="app">
        <h2>总价:{{totalPrice}}</h2>
    </div>
    <script>
        const vm = new Vue({
            el: "#app",
            data() {
                return {
                    books: [
                        { id: 110, name: "JavaScript从入门到入土", price: 119 },
                        { id: 111, name: "Java从入门到放弃", price: 80 },
                        { id: 112, name: "编码艺术", price: 99 },
                        { id: 113, name: "代码大全", price: 150 },
                    ]
                }
            },
            //原始方法
            /* computed:{
                totalPrice(){
                    let total = 0;
                    for(let i = 0;i < this.books.length;i++){
                        total += this.books[i].price;
                    }
                    return total;
                }
            } */
            
            //for...in可枚举的
            /* computed:{
                totalPrice(){
                    let total = 0;
                    for(let i in this.books){
                        total += this.books[i].price;
                    }
                    return total;
                }
            } */

            //for...of可迭代的
            /* computed:{
                totalPrice(){
                    let total = 0;
                    for(let item of this.books){
                        total += item.price;
                    }
                    return total;
                }
            } */

            // forEach
            /* computed:{
                totalPrice(){
                    let total = 0;
                    this.books.forEach(item => {
                        total += item.price;
                    });
                    return total;
                }
            } */

            //map方法,对数组元素进行操作,返回一个新的数组
            /* computed: {
                totalPrice() {
                    let total = 0;
                    this.books.map(item => {
                        total += item.price;
                    })
                    return total;
                }
            } */
            
            //对数组元素进行筛选,返回一个新的数组
            /* computed:{
                totalPrice(){
                    let total = 0;
                    this.books.filter(item=>{
                        total+=item.price;
                    })
                    return total;
                }
            } */

            //total初始值,没有初始值就是数组的第一个元素,item现在项,累加器。
            computed: {
                totalPrice() {
                    return this.books.reduce((total, item) => {
                        return  total + item.price
                    }, 0)
                }
            }
        })
    </script>
</body>

Logo

前往低代码交流专区

更多推荐