review: Array.sort - javascript

Example 1:
<html>
<body>

<script type="text/javascript">
Array.prototype.sort02=function(a,b){
  return -1;
}
var arr = new Array(6)
arr[0] = {"A":0};
arr[1] = {"A":1};
arr[2] = {"A":2};
arr[3] = {"A":3};
arr[4] = {"A":4};
arr[5] = {"A":5};


arr.sort(function(a,b){
// document.write("a.A"+a.A+"--b.A" + b.A+"<br/>");
 return 1;
});
document.write("Array.sort:----<br/>");
for (var i in arr){
  if(typeof(arr[i])=="object")
  document.write("arr["+i+"]:"+arr[i].A+"<br/>");
}
arr.sort02();

document.write("Array.sort02:----<br/>");
for (var i in arr){
  if(typeof(arr[i])=="object")
  document.write("arr["+i+"]:"+arr[i].A+"<br/>");
}
</script>

</body>
Result:--------------
Array.sort:----
arr[0]:5
arr[1]:4
arr[2]:3
arr[3]:2
arr[4]:1
arr[5]:0
Array.sort02:----
arr[0]:5
arr[1]:4
arr[2]:3
arr[3]:2
arr[4]:1
arr[5]:0

 Example 2:
----------------------------------
ar a2=[10,2,4,1,7];
a2.sort(); //1 ,10, 2, 4, 7 default sort by character.
function compare(value1,value2){
   if(value1<value2){return -1;}
   else if(value1>value2){return 2;}
   else {return 0;}
}
a2.sort(compare);//a2 : 1, 2, 4, 7, 10

评论

此博客中的热门博文

XML, XSL, HTML

Input in element.eleme.io

Data URI是由RFC 2397 ACE