如何对数字进行排序? [英] How to sort numbers?
问题描述
下面是代码:
<script type="text/javascript">
function sortNumber(a,b) {
return a - b;
}
var n = ["10", "5", "40", "25", "100", "1"];
document.write(n.sort(sortNumber));
</script>
sortNumber
函数用于对数字进行排序吗?a和b是什么意思,为什么存在?为什么 n.sort(sortNumber)
中的 sortNumber
没有指定 a
和 b
的任何参数?>
Is the sortNumber
function for sorting a number? What do a and b mean and why does it exist? Why sortNumber
in n.sort(sortNumber)
doesn't specify any parameter of a
and b
?
推荐答案
JavaScript sort()
函数可以或可以不使用参数.
该参数将是一个函数-意味着使用什么函数来评估两个元素中的哪个应该在另一个元素之前
.
The JavaScript sort()
function may or may not take a parameter.
The parameter would be a function - meaning what function is to be used to assess which of two elements should be before the other
.
n数组由表示数字的字符串组成.
做一个没有函数的简单 sort()
,将使用字母顺序:结果将是
The n array is made of strings representing numbers.
Doing a simple sort()
without a function, an alphabetical order would be used: the result would be
"1", "10", "25"... "5"
并且不正确.
提供一个函数 sortNumber
,告诉 sort
每次 sort
算法想要知道该函数时,使用数组的两个元素调用该函数这两个项目中的哪个在另一个之前.
Providing a function, sortNumber
, tells sort
to call that function with two elements of the array each time the sort
algorithm wants to know which of the two items is before the other.
因此提供两个项目的 sortNumber
进行了 numerical
操作以返回其中一个
Thus sortNumber
provided with two items, does a numerical
operation to return either
- 一个负值,表示 a 在 b 之前
- 一个正值, b 在 a 之前
- 零:它们在顺序方面相等(顺序无关紧要).
这篇关于如何对数字进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!