美文网首页
filter,map,reduce 用法

filter,map,reduce 用法

作者: 三人行大道 | 来源:发表于2019-12-01 09:16 被阅读0次
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    <div id="app">
        <ul>
            <li v-for="(item,index) in books">{{ index }}={{ item }}</li>
        </ul>
        <h2>{{ totalPrice }}</h2>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    
    <h2>
        filter/map/reduce
        filter中的回调函数有一个要求: 必须返回一个boolean值
        true: 当返回true时, 函数内部会自动将这次回调的n加入到新的数组中
        false: 当返回false时, 函数内部会过滤掉这次的n
    </h2>
    
    <script>
    
    
        const vm = new Vue({
            el:"#app",
            data:{
                names: ['why', 'kobe', 'james', 'curry'],
                books: [
                    {
                        id: 1,
                        name: '《算法导论》',
                        date: '2006-9',
                        price: 85.00,
                        count: 1
                    },
                    {
                        id: 2,
                        name: '《UNIX编程艺术》',
                        date: '2006-2',
                        price: 59.00,
                        count: 1
                    },
                    {
                        id: 3,
                        name: '《编程珠玑》',
                        date: '2008-10',
                        price: 39.00,
                        count: 1
                    },
                    {
                        id: 4,
                        name: '《代码大全》',
                        date: '2006-3',
                        price: 128.00,
                        count: 1
                    },
                ]
    
            },
            computed:{
                totalPrice(){
                    return this.books.reduce(function(pri,book){
                        // 第一个 pri是一个函数,第二个遍历出来的对象
                        return pri + book.price
                    },0)
                }
            },
            methods:{}
        })
    </script>
    
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:filter,map,reduce 用法

          本文链接:https://www.haomeiwen.com/subject/pdqzwctx.html