javascript - 自写的sort排序函数by()没起作用,请教bug出在哪里?
PHPz
PHPz 2017-04-10 12:45:01
[JavaScript讨论组]

看完《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'))));
PHPz
PHPz

学习是最好的投资!

全部回复(1)
天蓬老师

这里的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);
    }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号