Home  >  Article  >  Web Front-end  >  What is the method to arrange arrays in ascending and descending order in js?

What is the method to arrange arrays in ascending and descending order in js?

零下一度
零下一度Original
2017-04-28 10:29:322475browse

This article mainly introduces the method of JS to implement arrays in ascending and descending order, involving JavaScript implementation techniques for simple sorting operations of arrays. Friends in need can refer to the following

The examples in this article describe the JS implementation How to sort arrays in ascending and descending order. Share it with everyone for your reference, the details are as follows:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>数组数字大小排序</title>
</head>
<body>
  <p>让数组按照升序降序排列</p>
  <p>这里写个数组 var array=[1,80,4,33,21,55];</p>
  <p>升序输出:</p>
  <script type="text/javascript">
    var array=[1,80,4,33,21,55];
    array.sort(function (x,y) {
      return x-y;
    });
    document.writeln(array);
  </script>
  <p>解释:<br> x,y表示数组中的任意两个元素,若return > 0,则y前x;若reutrn < 0 ,则x前y后;当x=y时存在浏览器兼容。<br>简单来说:就是,x-y是按照从小到大排序,y-x是按照从大到小排序。</p>
  <p>顺手写个降序:</p>
  <script type="text/javascript">
    var array=[1,80,4,33,21,55];
    array.sort(function (x,y) {
      return y-x;
    });
    document.writeln(array);
  </script>
</body>
</html>

The operation effect diagram is as follows:

The above is the detailed content of What is the method to arrange arrays in ascending and descending order in js?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn