基础题
({} + {}).length => '[object Object][object Object]' 30([] + []).length => '' 0(function(){}).length => 0 函数length属性( 形参个数 )
对后台一些数据进行归类
let colors = [{id:'1', name:'red'},{id:'2', name:'blue'},{id:'3', name:'green'},{id:'4', name:'pink'}],persons = [{name: '小红', clothColor:'1,3'},{name: '小田', clothColor:'1,2'},{name: '小付', clothColor:'2,4'},{name: '小冯', clothColor:'3,4'}];//根据哪个种类,就先遍历哪个数组function classingFn(){let cache = {};colors.forEach((elem)=>{let _id = elem.id;cache[_id] = [];//遍历数据,进行分类persons.forEach((person)=>{let clothColorsArr = person.clothColor.split(',');if( clothColorsArr.includes(_id) ){cache[_id].push(person)}})})return cache}console.log(classingFn())
归类函数的封装,可以使用偏函数,先将关联数据传入,返回一个等待后续参数执行的函数。
考虑点:
(1)单一归类还是复合归类
(2)关联数据以什么字段进行归类
let colors = [{id:'1', color:'red'},{id:'2', color:'blue'},{id:'3', color:'green'},{id:'4', color:'pink'}],persons = [{name: '小红', clothColor:'1,3'},{name: '小田', clothColor:'1,2'},{name: '小付', clothColor:'2,4'},{name: '小冯', clothColor:'3,4'}];function classification ( sortArr, Data ){return function(foreign_key, sortingType){let cache = {};//先校验排序类别参数let correctSortingTypes = [ 'single', 'multi' ],isTypeCorrect = correctSortingTypes.includes(sortingType);if(!isTypeCorrect){let errorObj = new Error('invalid sortingType, only "single" and "multi" are accepted');console.log(errorObj);return}//先遍历分类数据sortArr.forEach((item)=>{let _id = item.id;cache[_id] = [];//遍历数据,进行分类Data.forEach((elem)=>{//判断归类类别let foreign_val = elem[foreign_key];if(sortingType === 'single'){if( _id === foreign_val){ cache[_id].push(elem) }}else{let arr = foreign_val.split(',');arr.forEach((singleId)=>{if(_id === singleId){ cache[_id].push(elem) }})}})})return cache}}
