JavaScript Tutorial/Array/Sort

Материал из Web эксперт
Перейти к: навигация, поиск

Array.sort()

Syntax



   <source lang="javascript">

array.sort()

   array.sort(function)</source>
   
  

Array.sort is case sensitive

   <source lang="javascript">

<html> <head> <title>Using the sort() method</title> <script type="text/javascript" language="javascript">

</script> </head> <body onload="SortElements()"> </body> </html></source>


Array.sort() with custom sorter

   <source lang="javascript">

<html> <head> <title>Using the sort() method on numbers and strings</title> <script type="text/javascript" language="javascript">

</script> </head> <body onload="SortElements()"> </body> </html></source>


Case-insensitive comparison

   <source lang="javascript">

<HTML> <HEAD> <TITLE> Case-insensitive comparison </TITLE> <HEAD>

  <BODY>

<SCRIPT> var theArray = new Array("a","N","M","T","r", "A", "q", "A",2); document.write ("Original array: " + theArray); document.write ("
"); theArray.sort(); document.write ("Default Sorted array: " + theArray); document.write ("
"); theArray.sort(function(x,y){ var a = String(x).toUpperCase(); var b = String(y).toUpperCase(); if (a > b) return 1 if (a < b) return -1 return 0; }); document.write ("Custom sorted array: " + theArray); </SCRIPT>

  </BODY>

</HTML></source>


Sort a string array

   <source lang="javascript">

<html> <head> <title>Using the sort() method</title> <script type="text/javascript" language="javascript">

</script> </head> <body onload="SortElements()"> </body> </html></source>


Using an alphabetical sort() method on strings

   <source lang="javascript">

<html> <head> <title>Using an alphabetical sort() method on strings</title> <script type="text/javascript" language="javascript">

</script> </head> <body onload="SortElements()"> </body> </html></source>


Using the sort() method on numbers and strings

   <source lang="javascript">

<html> <head> <title>Using the sort() method on numbers and strings</title> <script type="text/javascript" language="javascript">

</script> </head> <body onload="SortElements()"> </body> </html></source>


Using the sort() method on numbers and strings with custom sorter

   <source lang="javascript">

<html> <head> <title>Using the sort() method on numbers and strings</title> <script type="text/javascript" language="javascript">

</script> </head> <body onload="SortElements()"> </body> </html></source>