如何在JavaScript排序方法中对数字进行排序 [英] How to sort number in javascript sort method

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

问题描述

以下是代码:

 < 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 算法想要知道两个项目中的哪一个在另一个之前。



因此 sortNumber 提供两项,数字操作返回


  • a negativ e值,表示 a b

  • 之前为正值, b a

  • 零:它们在顺序上是相等的(顺序无关紧要)。

    Below is the code:

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

    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 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.

    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"
    

    and is not correct.

    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.

    Thus sortNumber provided with two items, does a numerical operation to return either

    • a negative value, meaning a is before b
    • a positive value, b is before a
    • zero: they're equal in terms of order (order doesn't matter).

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

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