2016-11-20 83 views
-1

这段代码必须有一些非常简单的错误,但它不会排序。这是为什么?javascript排序整数失败

$(document).ready(function() { 
      var topArray = []; 
      topArray.push(1000); 
      topArray.push(298); 
      topArray.push(2000); 
     topArray.sort(); 
      alert(topArray[0] + "," + topArray[1] + ", " + topArray[2]); 
     }) 

回答

0

附加排序选项吧,在这里要注意: http://www.w3schools.com/jsref/jsref_sort.asp

$(document).ready(function() { 
     var topArray = []; 
     topArray.push(1000); 
     topArray.push(298); 
     topArray.push(2000); 
    topArray.sort((function(a, b){return a-b})); 
     alert(topArray[0] + "," + topArray[1] + ", " + topArray[2]); 
    }) 
0

您需要按数字排序数字,而不是字符串,这是默认排序。

Description

如果未提供compareFunction,元件由在统一代码点以便将它们转换为字符串,并比较字符串排序。例如,“香蕉”出现在“樱桃”之前。在数字排序中,9在80之前,但由于数字被转换为字符串,“80”以Unicode顺序出现在“9”之前。

topArray.sort(function (a, b) { 
    return a - b; 
}); 
0

在基于字符串的比较,而不是默认Array#sort方法各种各样,实现自定义排序功能。

topArray.sort(function(a, b){ return a - b; }); 


MDN docs

如果的compareFunction不被供应,元件由在统一代码点以便将它们转换为字符串,并比较字符串排序。例如,“香蕉”出现在“樱桃”之前。 在数字排序中,9在80之前,但由于数字被转换为字符串,“80”以Unicode顺序排在“9”之前