当前位置:网站首页>JS' sort() function

JS' sort() function

2022-06-25 04:36:00 Liujiayi_

sort( )
- It can be used to sort the elements in the array
- It will also affect the original array , By default, it will follow Unicode Code to sort
Even for arrays of pure numbers , Use sort() Sorting time , I will also follow Unicode Code to sort ,

So when sorting numbers , You may get the wrong result .
We can specify the sorting rules by ourselves
We can do it in sort() Add a callback function , To specify the collation , Two formal parameters need to be defined in the callback function ,

The browser will use the elements in the array as arguments to call the callback function, and it is uncertain which element to call , But it's definitely in the array a It must be b in front

- The browser will determine the order of elements according to the return value of the callback function ,
If it returns a value greater than 0 Value , Then the element will exchange positions

If it returns a value less than 0 Value , Then the element position remains unchanged
If a day is returned , The two elements are considered equal , And don't exchange positions
for example :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var arr = [2, 4, 6, 7];
      arr.sort(function (a, b) {
        // Big in front 
        if (a > b) {
          return 1;
        } else if (a < b) {
          return -1;
        } else {
          return 0;
        }
      });
      console.log(arr);
    </script>
  </body>
</html>

 

原网站

版权声明
本文为[Liujiayi_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206250256377589.html