赞
踩
通常是为了实现引用类型数据的筛选,查找符合条件的对象
可以针对各种情况定义独立功能的过滤器,将过滤条件进行封装
如果有很多格式基本相同的数据,可以方便复用
- class Filter{
- constructor(filterHandler){
- this.filterHandler = filterHandler
- }
- filterFun(list){
- return list.filter(list => this.filterHandler(list))
- }
- }
-
- class CountryFilter extends Filter{
- constructor(country) {
- super(item => item.country === country)
- }
- }
- class GenderFilter extends Filter{
- constructor(gender) {
- super(item => item.gender === gender)
- }
- }
-
- const countryFilter = new CountryFilter('德玛西亚')
- const genderFilter = new GenderFilter('woman')
-
- const listArr = [
- {
- name:'wjt',
- country:'中国',
- gender:'man'
- },
- {
- name:'嘉文四世',
- country:'德玛西亚',
- gender:'man'
- },
- {
- name:'乐芙兰',
- country:'诺克萨斯',
- gender:'woman'
- },
- {
- name:'吉安娜.普罗德摩尔',
- country:'洛丹伦',
- gender:'woman'
- },
- ]
-
- const dmList = countryFilter.filterFun(listArr)
- const womanList = genderFilter.filterFun(listArr)
- console.log(dmList,'德玛西亚的人')
- console.log(womanList,'女性')
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。