localeCampare()方法與操作字符串有關的最后一個方法是localeCompare(),這個方法比較兩個字符串,并返回下列值中的一個:
◎如果字符串在字母表中應該排在字符串參數之前,則返回一個負數(大多數情況下是一1,具體的值要視實現而定);
◎如果字符串等于字符串參數,則返回0;
◎如果字符串在字母表中應該排在字符串參數之后,則返回一個正數(大多數情況下是l,具體的值同樣要視實現而定)。
以下是幾個側子:
var stringValue= "yellow";
alert(stringValue .localeCompare(”brick“)); //1
alert( stringValue.localeCompare(”yellow”)); //0
alert(stringValue .localeCompare(”zoo“)); //-1
這個例子比較了字符串”yellow”和另外幾個值:”brick u、”yellow”和“zoo”。因為”brick'在字母表中排在“yellow”之前,所以localeCompare()返回了1;而”yellow”等于nyellow”,所以localeCompare()返回了o;最后,”zoo”在字母表中排在“yellow”后面,所以localeCompare()運回了一1。再強調一次,因為lcaleCompare()返回的數值取決于實現,所以最好是像下面例子所示的這樣使用這個方法:
//使用localeCompare()的建議方式
function determineOrder (value) {
var result=stringValue.localeCompare (valuey;
if (result alert("The string 'yellow' comes before thd、string'"+value+"'"); } else if (result>0) { alert("The string 'yallow' comes after the string'"+Value+"'."); }else alert("The string 'yellow' is equal to the string'"+value+"'."); alert("The string'yellow'is equal to the strlng'"+value"',"); }
}
determineOrder( "brick");
determineOrder( "yellow");
determineOrder(“ZOO");
使用這種結構,就可以確保自己的代碼在任何實現中都可以正確地運行了。
localeCompare()方法比較與眾不同的地方,就是實現所支持的地區(qū)(國家和語言)決定了這個方法的行為。比如,美國以英語作為ECMAScript實現的標準語言,因此localeCompare()就是區(qū)分大小寫的,于是大寫字母在字母表中排在小寫字母前頭就成為了一頊決定性的比較規(guī)則。不過,在其他地區(qū)恐怕就不是這種情況了。