0

谁能告诉我如何使用javascript对下面的值数组进行排序。

var cols = new Array();
cols[0] = 13,000,000;
cols[1] = -20.45;
cols[2] = 0.0;
cols[3] = 10,000;
cols[4] = 750.00
cols[5] = 41.00;

我尝试了以下两种排序方法

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

结果如下所示。

cols[0] = -20.45;
cols[1] = 0.0;
cols[2] = 10,000;
cols[3] = 13,000,000;
cols[4] = 41.00;
cols[5] = 750.00

`

4

3 回答 3

1

I suggest you strip the commas so they can be converted to numbers using the +. Then you can use those numeric versions for comparison in your sorting functions.

http://jsfiddle.net/EuQTX/1/

var cols = new Array();
cols[0] = '13,000,000';
cols[1] = '-20.45';
cols[2] = '0.0';
cols[3] = '10,000';
cols[4] = '750.00';
cols[5] = '41.00';

//Removing the commas. You can add more characters to remove to the set
var pattern = /[,]/g

cols.sort(function (a,b){
  //remove unwanted characters so they can be converted to numbers
  a = +a.replace(pattern,'');
  b = +b.replace(pattern,'');
  //use the numeric versions to sort the string versions
  return a-b;
});

console.log(cols);
//["-20.45", "0.0", "41.00", "750.00", "10,000", "13,000,000"] 

Just a side note, you should declare arrays using the literal notation instead:

var cols = ["13,000,000", "-20.45", "0.0", "10,000", "750.00", "41.00"] 
于 2013-08-03T04:45:41.933 回答
0

Try with this:

var cols = ['13,000,000', '-20.45', '0.0', '10,000', '750.00', '41.00'];
cols.sort(function(a,b){
  var lhs = parseInt(a.replace(/,/g,""));
  var rhs = parseInt(b.replace(/,/g,""));
  return( lhs - rhs);
})
于 2013-08-03T04:48:34.193 回答
0

http://jsfiddle.net/M5LFg/4/

function sortBy(array, by) {
  return array
    .map(function (_) { return [ _, by(_) ]; })
    .sort(function (a, b) { return a[1] - b[1]; })
    .map(function (_) { return [ _[0] ]; });
}

sortBy(
  '13,000,000 -20.45 0.0 10,000 750.00 41.00'.split(' '),
  function (_) { return parseInt(_.replace(/,/g, ''), 10); }
)
于 2013-08-03T07:08:53.977 回答