标签:
<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[property];
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>
结果为:
标签:
原文地址:http://www.cnblogs.com/zhshlimi/p/4941915.html