近期需要使用对table数组排序,于是需要比较string类型的compare函数,找了一圈发现需要在XMLscript库中,http://www.w3school.com.cn/wmlscript/wmlscript_howto.asp这个网址中有,只是嫌麻烦,就自己写了一个。

//比较两个字符串的大小 默认str较大返回1否则返回-1,相同返回0
function compare(str,str1)
{
var length=(str.length-str1.length)>0?str1.length:str.length;
//alert(length);
var i=0,returnValue=0;
while(i<length)
{if( (str.charCodeAt(i)-str1.charCodeAt(i))>0 )
{ returnValue=1;return returnValue;}
if((str.charCodeAt(i)-str1.charCodeAt(i))==0)
{i++;}
if( (str.charCodeAt(i)-str1.charCodeAt(i))<0)
{returnValue=-1;return returnValue;}
}
if((str.length-str1.length)>0)
{returnValue=1;return returnValue;}
if((str.length-str1.length)<0)
{returnValue=-1;return returnValue;}
if((str.length-str1.length)==0)
{returnValue=0;return returnValue;}
}
//function compare

代码很简单,存着以后用的时候找得到

posted on 2013-06-04 16:25  songjie333  阅读(813)  评论(0编辑  收藏  举报