如何在JavaScript排序方法中对数字进行排序 [英] How to sort number in javascript sort method
问题描述
以下是代码:
< script type =text / javascript>
函数sortNumber(a,b)
{
return a - b;
var n = [10,5,40,25,100,1];
document.write(n.sort(sortNumber));
< / script>
我发现这是w3school,没有解释所有! sortnumber函数是对一个数字进行排序的公式吗? 什么是a和b以及它存在的原因
为什么n.sort中的sortNumber(sortNumber)没有指定a和b的任何参数?任何人都可以向我解释它吗?谢谢!!
参数是一个函数 - 意味着
使用什么函数来评估哪两个元素应该在另一个之前
n数组由表示数字的字符串组成。
做一个简单的 sort()
没有函数,将使用字母顺序:结果将会是
1,10 ,25...5
并且不正确。
提供函数 sortNumber
,告诉 sort
用两个元素调用该函数每次 sort
算法想要知道两个项目中的哪一个在另一个之前。
因此 Below is the code: I found this is w3school with no explain ay all!! Is sortnumber function is formula of sorting a number? What's mean a and b and why it exist?
why sortNumber in n.sort(sortNumber) doesn't specify any parameter of a and b?Can anyone explain it to me? Thanks!! The JavaScript The n array is made of strings representing numbers. and is not correct. Providing a function, Thus 这篇关于如何在JavaScript排序方法中对数字进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! sortNumber
提供两项,数字
操作返回
<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>
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
.
Doing a simple sort()
without a function, an alphabetical order would be used: the result would be "1", "10", "25"... "5"
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
provided with two items, does a numerical
operation to return either