comments | Javascript source | Execution result in your current browser |
default sort is alphabetically. Sorting modify the array in place | var a1=[1,2,3,4,10,20,30];
document.write("sort return: "+a1.sort()+"<br/>");
document.write("the array object: "+a1);
|
|
sort numerically | function numberAs(a,b) {
return a-b;
}
a1.sort(numberAs);
document.write(a1);
|
|
reverse an array | a1.reverse();
document.write(a1);
|
|
reverse again | a1.reverse();
document.write(a1);
|
|
sorting numerical, descending | function numberDes(a,b) {
return b-a;
}
a1.sort(numberDes);
document.write(a1);
|
|
string sorting, descending | function strDes(a, b) {
if (a>b) return -1;
else if (a<b) return 1;
else return 0;
}
var a2=["1", "a", "A", "b"];
a2.sort(strDes);
document.write(a2);
|
|