Web前端工作笔记001---封装前端数据字典_js 数组filter 总结_详解

版权声明:本文为博主原创文章,未经博主credreamer 允许不得转载 违者追究法律责任。 https://blog.csdn.net/lidew521/article/details/82823335
  JAVA技术交流QQ群:170933152 
我这里是我封装,前端数据字典的时候,用到的

//数据字典
var dic = function () {
    var dics;
    $.ajax({
        async: false,
        type: "get",
        url: constant.url.sc_admin.dic,
        dataType: 'JSON',
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            if (result.code == "200") {
                dics = (result.data.list);
            }
        }
    });

    return {
        getByTypeId: function (groupId) {
            var dictypes;
            dictypes = dics.filter(function (item) {
                return item.type == groupId;
            });
            return dictypes;
        },
        getByDictId: function (groupId, dictId) {
            var dictypeids;
            dictypeids = dics.filter(function (item) {//这里用到的
                return (item.type == groupId) && (item.name == dictId);
            });
            return dictypeids[0];
        },
        getByDictValue: function (groupId, dictValue) {
            var dictypevalues;
            dictypevalues = dics.filter(function (item) {
                return (item.type == groupId) && (item.code == dictValue);
            });
            return dictypevalues[0];
        }
    }
}();

--------------------------------------------------------

fi-----------------lter过滤数组

filter() 
1.方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素 
2.不会改变原始数组

var arr = [
  { id: 1, text: 'aa', done: true },
  { id: 2, text: 'bb', done: false }
]
console.log(arr.filter(item => item.done))
  •  

转成ES5

arr.filter(function (item) {
  return item.done;
});
  •  

return后面判断结果,取布尔值,true的话就添入新的filter数组中,false的话,不会添进filter的数组中。

最后得到新的数组是

[{id: 1, text: "aa", done: true}]
  •  
var arr = [
  { id: 1, text: 'aa', done: true },
  { id: 2, text: 'bb', done: '' }
]
console.log(arr.filter(item => item.done))
  •  

结果还是一样,因为”空字符串转成布尔类型为false

用处

1.去掉数组中的空字符串项

var arr = ['1.jpg','2.jpg','', '3.jpg',' ']
var newArr = arr.filter(item => item)
console.log(newArr,arr)
  •  
newArr => ["1.jpg", "2.jpg", "3.jpg", " "]   空字符串项被过滤掉了
arr => ["1.jpg", "2.jpg", "", "3.jpg", " "]
  •  

2.去掉数组中不符合的项

var arr = [73,84,56, 22,100]
var newArr = arr.filter(item => item>80)   //得到新数组 [84, 100] 
console.log(newArr,arr)
  •  
var arr = ['aa','cb','cc', 'bd','rf']
var newArr = arr.filter(item => item.indexOf('b')<0) 不包含b字符串的

得到新数组 ["aa", "cc", "rf"] 

猜你喜欢

转载自blog.csdn.net/lidew521/article/details/82823335