Array.prototype._killSpaceFun = function(res){return res.replace(/\s/g,"");}
Array.prototype._whereFun = function(row,conditions){
var fs = [];
conditions.forEach(function(item,index){
var key = item.key;
var val = item.value;
var type = item.type;
var flg = false;
var v = row[key];
if(typeof v != "undefined"){
switch(type){
case "==":
flg = (v == val);
break;
case "!=":
flg = (v != val);
break;
case "%%":
flg = (String(v).toLowerCase().indexOf(String(val)) >= 0);
break;
case "!%":
flg = (String(v).toLowerCase().indexOf(String(val)) < 0);
break;
case "#%":
flg = (String(v).substr(0,String(val).length) == String(val));
break;
case "%#":
flg = (String(v).substr(String(val).length,String(v).length) == String(val));
break;
case ">":
flg = (Number(v) > Number(val));
break;
case ">=":
flg = (Number(v) >= Number(val));
break;
case "
flg = (Number(v) < Number(val));
break;
case "<=":
flg = (Number(v) <= Number(val));
break;
default:
flg=false;
break;
}
fs.push(flg);
}
});
return !fs.includes(false);
}
Array.prototype._formatFun = function(cond){
var cc = ["%%","#%","%#","!%","==","!=",">=","<=",">","
var cl = [];
var ret = null;
cc.forEach(function(item,index){
if(ret == null){
if(cond.indexOf(item)>=0){
var sm = cond.split(item);
ret = {"key":sm[0]};
ret.type = item;
ret.value = sm.length >= 1 ? sm[1] : null;
if(ret.value == null){ret=null;}
}
}
})
return ret;
};
Array.prototype.itemSelect = function(fields,where,igCase){
igCase = typeof igCase == "undefined" ? true : Boolean(igCase);
where = typeof where == "undefined" ? "" : String(where);
where = igCase == true ? where.toLowerCase() : where;
fields = this._killSpaceFun(fields);
var flds = igCase == true ? this._killSpaceFun(fields).toLowerCase().split(",") : this._killSpaceFun(fields).split(",");
var src_conds = this._killSpaceFun(where).split("&&");
var obj_conds = [];
src_conds.forEach(function(item,index){
var cond = obj_conds._formatFun(item);
if(cond!=null){
obj_conds.push(cond);
}
});
var _ls = [];
this.forEach(function(item,index){
if(obj_conds._whereFun(item,obj_conds)){
if(fields == "*" || fields == ""){
_ls.push(item);
}else{
var _row = {};
flds.forEach(function(key,idx){
_row[key] = typeof item[key] == "undefined" ? null : item[key];
});
_ls.push(_row);
}
}
});
return _ls;
}
试下这个,无聊的时候测试的产物。
使用如下
var list = [{id:1,"name":"a"},{id:2,"name":"aa"},{id:3,"name":"bbb"}];
//查询基本语法,array.itemSelect("字段列表","条件")
//==:等于
//>=:大于等于
//<=:小于等于
//%%:%A%
//#%:A%
//%#:%A
//!=:不等于
//>:大于
//<:>
list.itemSelect("id,name","id > 1");