数组的遍历

前端遍历数组的方式很多,记录一下

<body>
    <div id="app">
        <h2>{{TotalPrice}}</h2>
    </div>
    <script>
        const app = new Vue({
            el: '#app',
            data: {
                books: [{ id: 110, name: 'a1', price: 119 },
                    { id: 111, name: 'a2', price: 120 },
                    { id: 112, name: 'a3', price: 121 }]
            },
            //计算属性
            computed: {
                fullname: function () {
                    return this.firstName + " " + this.lastName;
                },
                TotalPrice: function () {
                    let result = 0;
                    for (let i = 0; i < this.books.length; i++) {
                        result += this.books[i].price;
                    }
                    for (let i in this.books) {
                        result += this.books[i].price;
                    }
                    for (let i of this.books) {
                        result += i.price;
                    }//注意of是类似于foreach的 直接取的对象
                     result =this.books.map(n => n.price).reduce((pre,n) => pre + n);
                    return result;
                }
            }
        })
    </script>
</body>

 

posted @ 2020-04-21 00:43  hurui12  阅读(125)  评论(0编辑  收藏  举报