How to sort an array of floats in JavaScript?

后端 未结 4 1120
甜味超标
甜味超标 2021-01-15 21:10

I tried below example but now working with correct information.

var fruits = [110.111, 1245.22222, 2.458, 0.001];
fruits.sort();
document.write(fruits);
         


        
4条回答
  •  忘掉有多难
    2021-01-15 22:05

    You can use a custom sort function like this:

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

    Array.sort() method treats numbers as strings, and orders members in ASCII order.

提交回复
热议问题