简单的字符串数组排序就一句话
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>
结果为:
console.log("名称降序排序前"+list.toString());
list.sort(Sort("name",false));
console.log("名称降序排序后"+list.toString());