📌  相关文章
📜  如何使用 JavaScript 对表中的行进行排序?

📅  最后修改于: 2021-11-08 05:45:26             🧑  作者: Mango

由于 JavaScript 不提供任何内置函数来对表格进行排序,因此我们将需要使用本机方法对给定的表格进行排序。我们将研究本文中的方法。

方法:
以下两个示例都将使用基本算法和类似方法。循环程序对元素进行切换和排序,直到排序完毕。

// executes on action like button click
Function() {   
   // main loop that runs until table is sorted
   While (condition = true) {   
      // runs for all rows
      for (i = 1; i < row.length; i++ ) {   
         // check if switch is required
         if (element_A > element_B){   
            // perform switch
            PerformSwitch();   
         }
      }
   }
}

示例 1:本示例使用while循环对表进行排序以切换行,直到对行进行排序。



  

    GeeksforGeeks
    

  

  
    
        

GeeksforGeeks

        

                     

                                                                                                                                                                                                                                                                                                                                   
CountryCapital
United states of AmericaWashington DC
IndiaNew Delhi
AustraliaCanberra
GermanyBerlin
                
  

点击前输出:
未排序表

点击后输出:
排序表

示例 2:此示例使用相同的循环技术对表进行排序,但对给定的列以及两个方向(升序和降序)都执行该函数。



  

    GeeksforGeeks
    

  

    
        

          GeeksforGeeks       

           

          Click the headers to sort in            ascending and descending.           

                                                                                                                                                                                                                                                                                                                                                 
CountryCapital
United states of AmericaWashington DC
IndiaNew Delhi
AustraliaCanberra
GermanyBerlin
                
  

排序前输出
未排序表 2

第一列排序的输出(升序):
排序表 2

第二列排序的输出(降序):
排序表 2 降序