首页 > 自写的sort排序函数by()没起作用,请教bug出在哪里?

自写的sort排序函数by()没起作用,请教bug出在哪里?

看完《javascript语言精粹》中的array.sort(comparefn)一节(Page81),很有启发性,于是自己试着实现这样一个通用函数by:无论数组对象为何种类型,调用此函数就能实现人们一般认知意义上的排序。
函数写完,发现没有起作用,debug了好久,最后还是决定求助SF的各位了!

	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'))));

这里的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);
    }
}
【热门文章】
【热门文章】