T086ѧϰ�� | վ��ѧԺ | �����ĵ� | ���� | Ъ���� | IP��ַ��ѯ | �������� | ���ջ��� | �����ֵ� | ���ù��� | ������Ϣ��ѯ

Javascript����sort�������

�� �������ߣ����� ����ʱ�䣺2008-02-11 | ���壺�� �� С��
[����]����javascript �� Array.sort()���������������������������� ��Ĭ���������ǽ����������У�ʵ���������£� �� var arrA = [6,2,4,3,5,1];arrA.sort();document.writeln(arrA); ����//�����ǣ�1,2,3,4,5,6 ����...

����javascript �� Array.sort()���������������������������� ��Ĭ���������ǽ����������У�ʵ���������£� ��

var arrA = [6,2,4,3,5,1];
arrA.sort();
document.writeln(arrA);

����//�����ǣ�1,2,3,4,5,6

����sort() �������Խ���һ�� ����Ϊ���� �����������������������ֱ�����ÿ�������Ƚ�ʱ�����������sort()����ʱÿ�αȽ������������ִ���������������������Ƚϵ���������Ϊ�������ݸ���������������������ֵΪ1��ʱ���ͽ���������������˳�򣬷����Ͳ�������

����ʵ�����£�

��var arrA = [6,2,4,3,5,1];
��/**//*arrA.sort();
��document.writeln(arrA);
��*/
��function desc(x,y)
��...{
������if (x > y) ��
����������return -1;
������if (x < y) ����������
����������return 1;
��}
��function asc(x,y)
��...{
������if (x > y) ��
����������return 1;
������if (x < y) ����������
����������return -1;
��}
��arrA.sort(desc); ��// sort by desc
��document.writeln(arrA);
��document.writeln("<br>");
����arrA.sort(asc); ��//sort by asc
��document.writeln(arrA);

����//����������

����6,5,4,3,2,1

����1,2,3,4,5,6

�������⣬����ֱ�Ӱ�һ����������ֱ�ӷŵ�sort()�����ĵ����С����µ������ǽ���������ǰ�棬ż�����ں��棬�������£�

������var arrA = [6,2,4,3,5,1];
������arrA.sort( function(x, y) ...{
����������if (x % 2 ==0) ��
��������������return 11;
����������if (x % 2 !=0) ��������
��������������return -1;��
����������}
������);
������document.writeln(arrA);

����//������1,5,3,4,6,2

  • ת����ע����Դ��ITѧϰ�� ��ַ��http://www.t086.com/ �����������Ƽ�������
  • �ر������� ��վ�������ر�������ֹת�ص�ר�������������¿�������ת�أ���������ע��������ԭʼ���ߡ����°�Ȩ������ԭʼ�������С����ڱ���վת�����µĸ��˺���վ�����DZ�ʾ������л�⡣������վת�ص������а�Ȩ��������ϵ���ǣ����ǻᾡ�����Ը�����
������ѯ Health Check Gulangyu
© 2017 T086ѧϰ�� - T086.com(ԭitlearner.com)
RunTime:18.62ms QueryTime:7