日期:2014-05-16  浏览次数:20390 次

javascript sort的排序问题
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=" http://www.w3.org/1999/xhtml">
 <head>
  <title></title>
 <script type="text/javascript">
  //var a = new Array(1,2,3);
  /*var a = [6,10,1,2,3];
  a.sort();
  document.write(a); //1,10,2,3,6
  */
  var arr = new Array(33,44,11,22);
  arr.sort();
  alert(arr);
  arr.sort(function(a,b){
  return a-b;
  });
  alert(arr);
  
 </script>
 </head>
 
 <body>
 </body>
</html>

为什么排序不成功?



------解决方案--------------------
arr.sort();应该返回的是个新对象了吧
你任然显示arr对象 肯定是有问题的嘛
 
------解决方案--------------------
sort()方法是直接对原数组进行修改的。
------解决方案--------------------
sort()函数不产生数组副本,是对原数组的排序
function( a,b){ if( a<b) return -1;If(a==b) return 0; if( a>b) return 1;}

------解决方案--------------------
如果调用sort方法时没有使用参数,将按字母顺序对数组中的元素进行排序,因此10会排到2的前面