闭包->类的实例数组排序

时间:2021-09-12 10:31:09

简单的字符串数组排序就一句话

Arr.sort(function(s1,s2){return s1.localeCompare(s2));//升序

Arr.sort(function(s1,s2){return -1*s1.localeCompare(s2));//降序

但是对应复杂的实例数组就不能这样了!

<script>
function Person(name,age)
{
if(this instanceof Person)//如果是 new
{
this.name=name;
this.age=age;
}
else return new Person(name,age); //如果是当函数调用,则直接new自己

}
Person.prototype.toString=function()
{
return "name:"+this.name+"\tage:"+this.age;
}
var list=[];
list[0]=new Person("张三",20);

list[1]=new Person("李四",30);

list[2]=new Person("王五",25);

list[3]= Person("刘六",40);
Array.prototype.toString=function()
{
var str="";
for(var i=0;i<this.length;i++)
{
str+=this[i].toString()+",";
}
return str;
}
function Sort(property,sortByAsc)
{

return function (object1,object2)
{
var v1=object1[property];
var v2=object2[p

roperty];

if(/^[\u4e00-\u9fa5]/.test(v1))

//汉字比较简单的就是一句话

return sortByAsc? v1.localeCompare (v2):-1*v1.localeCompare (v2);

else{
if(sortByAsc)
{
if(v1>v2)return 1;//备注:汉字不建议直接这样比较大小,结果也不准确
else if(v1<v2)return -1;
return 0;
}
else
{
if(v1>v2)return -1;
else if(v1<v2)return 1;
return 0;
}

}
}
}
console.log("年龄升序排序前"+list.toString());
list.sort(Sort("age",true));
console.log("年龄升序排序后"+list.toString());
</script>

结果为:

年龄升序排序前name:张三 age:20,name:李四 age:30,name:王五 age:25,name:刘六 age:40,  
年龄升序排序后name:张三 age:20,name:王五 age:25,name:李四 age:30,name:刘六 age:40,

console.log("名称降序排序前"+list.toString());
list.sort(Sort("name",false));
console.log("名称降序排序后"+list.toString());

 结果为:
名称降序排序前name:张三 age:20,name:李四 age:30,name:王五 age:25,name:刘六 age:40, 
名称降序排序后name:张三 age:20,name:王五 age:25,name:刘六 age:40,name:李四 age:30,