Home > Web Front-end > JS Tutorial > body text

JavaScript sorting function implements numerical sorting_javascript skills

WBOY
Release: 2016-05-16 15:52:29
Original
1233 people have browsed it

Javascript sorting function implements numerical sorting

<script>
function SortNumber(obj,func) //定义通用排序函数
{
//参数验证,如果第一个参数不是数组或第二个参数不是函数则抛出异常
if(!(obj instanceof Array) || !(func instanceof Function)) 
{
var e = new Error(); //生成错误信息
e.number = 100000; //定义错误号
e.message = "参数无效"; //错误描述
throw e; //抛出异常
}
for(n in obj) //开始排序
{
for(m in obj)
{
if(func( obj[n],obj[m]) ) //使用回调函数排序,规则由用户设定
{
var tmp = obj[n]; //创建临时变量
obj[n] = obj[m]; //交换数据
obj[m] = tmp;
}
}
}
return obj; //返回排序后的数组
}
function greatThan(arg1,arg2) //回调函数,用户定义的排序规则
{
return arg1 < arg2;
}
try
{
var numAry = new Array(5,8,6,32,1,45,6,89,9); //生成一数组
document.write("<li>排序前:"+numAry); //输出排序前的数组
SortNumber(numAry,greatThan); //调用排序函数
document.write("<li>排序后:"+numAry); //输出排序后的数组
}
catch(e)
{
alert(e.number+":"+e.message);
}
</script>
Copy after login

The above is the entire content of this article, I hope you all like it.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template