题目
自己实现find方法,达到这样输出的效果
// data参数
var data = [{
userId: 8,
title: 'title1'
},
{
userId: 11,
title: 'title2'
},
{
userId: 15,
title: 'title3'
},
];
// 调用find方法
find(data).where(x => x.userId > 8).orderBy('userId', 'desc')
// 返回结果:
[{"userId":11,"title":"title2"},{"userId":15,"title":"title3"}]
实现代码
function find(arr) {
Array.prototype.where = where;
Array.prototype.orderBy = orderBy;
return arr;
}
function where(filter) {
// 根据需要定制
return this.filter(filter);
}
function orderBy(field, sortMethod) {
if (sortMethod == 'asc') {
this.sort((x, y) => x[field] - y[field]);
} else if (sortMethod == 'desc') {
this.sort((x, y) => y[field] - x[field]);
}
return this;
}
find(obj).where(x => x.userId > 8).orderBy('userId','desc');