If you supply a function in the sortFunction argument, it must return one of the following values: A negative value if the first argument passed is less than the second argument. Zero if the two arguments are equivalent. A positive value if the first argument is greater than the second argument 如果想要按其他顺序进行排序,必须提供比较函数,该函数要比较两个值,然后返回一个用于说明这两个值的相对顺序的数字。 象下面的 function SortDemo(a,b){
return a - b; } var m, l,k; m = new Array("8989" ,"3445" ,"134", "67", "878","3454","878"); k=m.sort(); l = m.sort(SortDemo); alert(k); alert(l);
两个例子中都涉及, function SortDemo(a,b){ return a - b; }a-b代表什么?传入这个函数里的值又是???什么??呢 我看不到有什么值传进去,,唉
<script >
function KeyValue(serialkey,value)
{
this.serialkey = serialkey;
this.value = value;
}
function sortfunction(x,y)
{
return x.serialkey -y.serialkey;
}
var a=new Array(3);
a[0]=new KeyValue(30,'aaa');
a[1]=new KeyValue(10,'ddd');
a[2]=new KeyValue(20,'ccc');
a.sort(sortfunction);
window.alert(a[1].value);
</script>
Zero if the two arguments are equivalent.
A positive value if the first argument is greater than the second argument
如果想要按其他顺序进行排序,必须提供比较函数,该函数要比较两个值,然后返回一个用于说明这两个值的相对顺序的数字。
象下面的
function SortDemo(a,b){
return a - b;
}
var m, l,k;
m = new Array("8989" ,"3445" ,"134", "67", "878","3454","878");
k=m.sort();
l = m.sort(SortDemo);
alert(k);
alert(l);
function SortDemo(a,b){
return a - b;
}a-b代表什么?传入这个函数里的值又是???什么??呢
我看不到有什么值传进去,,唉
.零,如果两个参数相等。
.正值,如果第一个参数比第二个参数大。然后sort把数组中的每两个元素按sortfunction的两个参数传入,比较后排序。如“guoweidong(※『孤独~寂)”的例子:数组a的每个元素都是KeyValue(非数字)这样没法对数组直接排序,可以用sortfunction定义其排序方式:按照每个元素的serialkey升序排列。sortfunction就是一个数组元素排序的计算规则。其中的x,y两个参数可以理解为代表数组中任意两个元素。