基础题

    1. ({} + {}).length => '[object Object][object Object]' 30
    2. ([] + []).length => '' 0
    3. (function(){}).length => 0 函数length属性( 形参个数 )

    对后台一些数据进行归类

    1. let colors = [
    2. {id:'1', name:'red'},
    3. {id:'2', name:'blue'},
    4. {id:'3', name:'green'},
    5. {id:'4', name:'pink'}
    6. ],
    7. persons = [
    8. {name: '小红', clothColor:'1,3'},
    9. {name: '小田', clothColor:'1,2'},
    10. {name: '小付', clothColor:'2,4'},
    11. {name: '小冯', clothColor:'3,4'}
    12. ];
    13. //根据哪个种类,就先遍历哪个数组
    14. function classingFn(){
    15. let cache = {};
    16. colors.forEach((elem)=>{
    17. let _id = elem.id;
    18. cache[_id] = [];
    19. //遍历数据,进行分类
    20. persons.forEach((person)=>{
    21. let clothColorsArr = person.clothColor.split(',');
    22. if( clothColorsArr.includes(_id) ){
    23. cache[_id].push(person)
    24. }
    25. })
    26. })
    27. return cache
    28. }
    29. console.log(classingFn())

    归类函数的封装,可以使用偏函数,先将关联数据传入,返回一个等待后续参数执行的函数。
    考虑点:
    (1)单一归类还是复合归类
    (2)关联数据以什么字段进行归类

    1. let colors = [
    2. {id:'1', color:'red'},
    3. {id:'2', color:'blue'},
    4. {id:'3', color:'green'},
    5. {id:'4', color:'pink'}
    6. ],
    7. persons = [
    8. {name: '小红', clothColor:'1,3'},
    9. {name: '小田', clothColor:'1,2'},
    10. {name: '小付', clothColor:'2,4'},
    11. {name: '小冯', clothColor:'3,4'}
    12. ];
    13. function classification ( sortArr, Data ){
    14. return function(foreign_key, sortingType){
    15. let cache = {};
    16. //先校验排序类别参数
    17. let correctSortingTypes = [ 'single', 'multi' ],
    18. isTypeCorrect = correctSortingTypes.includes(sortingType);
    19. if(!isTypeCorrect){
    20. let errorObj = new Error('invalid sortingType, only "single" and "multi" are accepted');
    21. console.log(errorObj);
    22. return
    23. }
    24. //先遍历分类数据
    25. sortArr.forEach((item)=>{
    26. let _id = item.id;
    27. cache[_id] = [];
    28. //遍历数据,进行分类
    29. Data.forEach((elem)=>{
    30. //判断归类类别
    31. let foreign_val = elem[foreign_key];
    32. if(sortingType === 'single'){
    33. if( _id === foreign_val){ cache[_id].push(elem) }
    34. }else{
    35. let arr = foreign_val.split(',');
    36. arr.forEach((singleId)=>{
    37. if(_id === singleId){ cache[_id].push(elem) }
    38. })
    39. }
    40. })
    41. })
    42. return cache
    43. }
    44. }