为了账号安全,请及时绑定邮箱和手机立即绑定

函数写完,发现没有起作用,debug了好久,最后还是决定求助imooc的各位了!

函数写完,发现没有起作用,debug了好久,最后还是决定求助imooc的各位了!

茅侃侃 2023-05-01 14:10:43
看完《javascript语言精粹》中的array.sort(comparefn)一节(Page81),很有启发性,于是自己试着实现这样一个通用函数by:无论数组对象为何种类型,调用此函数就能实现人们一般认知意义上的排序。 var by = function (name,minor){ return function (a,b){ var objBy =  function (a,b){ var aValue,bValue; aValue = a[name]; bValue = b[name]; if (aValue === bValue){ return typeof minor === 'function' ? minor(a,b) : 0; } if (typeof aValue === typeof bValue){ return aValue < bValue ? -1 : 1; } return typeof aValue < typeof bValue ? -1 : 1; } var generalBy  = function (a,b){ if (a === b){ return 0; } if (typeof a === 'string' && typeof b === 'string'){ return a.localeCompare(b); } if (typeof a === typeof b){ return a < b ? -1 : 1; } return typeof a < typeof b ? -1 : 1; } if (a && b && typeof a ==='object' && typeof b === 'object'){ return objBy; } return generalBy; } }         //test var arry1 = [8,90,10,2,100,34,35,12]; var arry2 = [4,20,10,34,"hello word","杀星","my god","哈哈哈","高级编程","爱情","四货","一个人" ,"大人"]; var arry3 = [{name:"maggie",sex:"famale",age:43},{name:"gino",sex:"male",age:28},{name:"laura",sex:"famale",age:20},{name:"tino",sex:"male",age:25},{name:"amy",sex:"famale",age:27}]; console.log(arry1.sort(by())); console.log(arry2.sort(by())); console.log(arry3.sort(by('sex',by('age'))));
查看完整描述

1 回答

?
心有法竹

TA贡献1866条经验 获得超5个赞

这里的by应该返回的是一个比较函数,你这里返回的是一个“返回比较函数”的函数,所以应该改为(注意最后的改动):

var by = function (name, minor) {    return function (a, b) {        var objBy = function (a, b) {            var aValue, bValue;
            aValue = a[name];
            bValue = b[name];            if (aValue === bValue) {                return typeof minor === 'function' ? minor(a, b) : 0;
            }            if (typeof aValue === typeof bValue) {                return aValue < bValue ? -1 : 1;
            }            return typeof aValue < typeof bValue ? -1 : 1;
        }        var generalBy = function (a, b) {            if (a === b) {                return 0;
            }            if (typeof a === 'string' && typeof b === 'string') {                return a.localeCompare(b);
            }            if (typeof a === typeof b) {                return a < b ? -1 : 1;
            }            return typeof a < typeof b ? -1 : 1;
        }        if (a && b && typeof a === 'object' && typeof b === 'object') {            return objBy(a,b);
        }        return generalBy(a,b);
    }
}
查看完整回答
反对 回复 2023-05-03
  • 1 回答
  • 0 关注
  • 67 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信