品一品编程 --- 3

作者: Candy程 | 来源:发表于2017-04-12 18:00 被阅读0次
    问题描述:

    实现链式调用

    var origin = [
        {id:1,title:'title1',name:'tom'},
        {id:2,title:'abcd2',name:'d1'},
        {id:3,title:'title2',name:'d34'},
        {id:4,title:'efg',name:'df4'}
    ];
      
    var find = function(data){  
        // your code here  
    }  
      
    var result = find(origin).where({'title':/\d$/}).order('id','desc'); //desc 非递增  
    console.log(result);  //  [{id:3,title:'title2'},{id:1,title:'title1'}]  
    
    程序如下:
    var find = function(data){
       var _this = this //减少对全局变量的访问
        _this.data = data
        _this.where = function(obj) {
            var keys = Object.keys(obj) 
            for(var key in keys) { //实现多条件下筛选
                var reg = obj[key]
                _this.data = _this.data.filter(function(x){
                    return reg.test(x[key])
                })
            }
            return _this
        }
        _this.order = function(key,type) {
            if(type === 'desc') {
                return _this.data.sort(function(s1,s2) { //降序
                    return s2[key] - s1[key]
                })
            }
            else {
                return _this.data
            }
        }
        return {
            data: this.data,
            where: this.where,
            order: this.order
        }
    }
    

    相关文章

      网友评论

        本文标题:品一品编程 --- 3

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