如何JavaScript的排序功能的工作(作为算法)? [英] How does the JavaScript sort function work(as an algorithm)?

查看:114
本文介绍了如何JavaScript的排序功能的工作(作为算法)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

中的JavaScript 排序函数,它接受一个参数允许一个传递函数。

The JavaScript sort function which takes a parameter allows one to pass in a function.

例如:

var myarray=[25, 8, 7, 41]
myarray.sort(function(a,b){return a - b}) //Array now becomes [7, 8, 25, 41]

它是如何在code

How is it that the code

function(a,b)
{
return a - b
}

PTED是要提升跨$ P $?它应该被分为三种情况,℃下,== 0,和> 0;但如何这是否有意义时, A B 可以是任何东西?

is interpreted to be ascending? It's supposed to be divided into three cases, <0 , ==0, and >0 ; but how does this make sense when a and b can be anything?

感谢您!

推荐答案

原因回答你的问题是特别棘手的,或者至少在细节,是因为没有规范的,说其排序算法浏览器应该实现。所以告诉你它具体是如何工作在一个浏览器浏览器之间可能存在差异,甚至是随时间而变化。

The reason answering your question is especially tricky, or at least in detail, is because there is no specification that says which sorting algorithm a browser should implement. So telling you specifically how it works on one browser may differ between browsers, or even change over time.

它的要点是,虽然,要想到一个和b作为是任何两个值。如果你正在返回的一的结果 - B,那么你的排序变为升序排序。如果你做B - 是,那么它​​是按降序排列

The gist of it is though, you want to think of "a" and "b" as being any two values. If you are returning the result of "a" - "b", then your sort goes in ascending order. If you do "b" - "a", then it is in descending order.

的妙处使自己的排序功能,就是可以在一个单独的函数处理他们之后的a和b的值进行比较。因此,可以说你想用摄氏温度值进行排序,但你只有在华氏阵列。你可以这样做:

The neat thing about making your own sort functions, is that you can compare the value of "a" and "b" after processing them in a separate function. So lets say you want to sort by the Celsius values, but your array in only in Fahrenheit. You can do something like:

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

这篇关于如何JavaScript的排序功能的工作(作为算法)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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