# 链式数组操作
const list = [
{
age: 1,
id: 2,
name: "江",
},
{
age: 18,
id: 3,
name: "张",
},
{
age: 21,
id: 1,
name: "李",
},
{
age: 8,
id: 4,
name: "王",
},
{
age: 23,
id: 5,
name: "刘",
},
];
function Query(list) {
this.list = list;
}
Query.prototype.where = function(cb) {
this.list = this.list.filter(cb);
return this;
};
Query.prototype.sortBy = function(key) {
this.list.sort((a, b) => a[key] - b[key]); // 升序排列
return this;
};
Query.prototype.execute = function() {
return this.list;
};
function query(list) {
return new Query(list);
}
const result = query(list)
.where((item) => item.age >= 18)
.sortBy("id")
.execute();
console.log(result);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56