JavaScript Tutorial/Array/Sort
Содержание
- 1 Array.sort()
- 2 Array.sort is case sensitive
- 3 Array.sort() with custom sorter
- 4 Case-insensitive comparison
- 5 <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>
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>