如何在JavaScript中对浮点数组进行排序? [英] How to sort an array of floats in JavaScript?

查看:76
本文介绍了如何在JavaScript中对浮点数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下示例,但现在正在使用正确的信息。

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);

结果:

0.001,110.111,1245.22222,2.458

但我想要这样的东西

0.001,2.458,110..111,1245.22222

此代码有什么问题?

推荐答案

array.sort( [compareFunction] 使用可选功能作为自定义比较器

array.sort([compareFunction]) takes an optional function which works as a custom comparator

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

如果你想降序排序

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






via: MDN Array.prototype.sort docs


  • 如果 compareFunction(a,b)小于0,则将a排序为低于b的索引,即a先来。

  • 如果 compareFunction(a,b)返回0,则a和b相互保持不变,但是根据所有不同的元素排序。注意:ECMAscript标准不保证这种行为,因此并非所有浏览器(例如可追溯到至少2003年的Mozilla版本)都尊重这一点。

  • 如果 compareFunction( a,b)大于0,将b排序为低于a的索引。

  • compareFunction(a,b)必须始终返回相同的值。如果返回不一致的结果,则排序顺序未定义

  • If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
  • compareFunction(a, b) must always returns the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined

最近,我已经一直在做一些函数式编程。对于想要以不同方式解决同一问题的人来说,我会将此部分作为另一种选择。

Lately, I've been doing some functional programming. I'll leave this section as another option for people that want to solve the same problem in different ways.

首先,我们有一些通用的实用功能。当我们想要定义更高阶 asc desc 排序函数时,这些是必要的。

First we have some general utility functions. These will be necessary when we want to define our higher order asc and desc sorting functions.

const sub = x => y => y - x;
const flip = f => x => y => f (y) (x);
const uncurry = f => (x,y) => f (x) (y);
const sort = f => xs => xs.sort(uncurry (f));

现在您可以轻松定义 asc desc sub而言

Now you can easily define asc and desc in terms of sub

const asc = sort (flip (sub));
const desc = sort (sub);

检查出来

asc ([4,3,1,2]);  //=> [1,2,3,4]
desc ([4,3,1,2]); //=> [4,3,2,1]

您仍然可以使用<$ c $进行自定义排序c> sort(比较器)(someData)

// sort someData by `name` property in ascending order
sort ((a,b) => a.name - b.name) (someData); //=> ...

这篇关于如何在JavaScript中对浮点数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆