JS字符串比較

 

There are five methods to compare strings.


1.Equality == True if operands are the same; otherwise false
e.g.
var sVal = "this"; if (sVal == "this) // trueapp

 

2.Strict equality === True if operands are the same, and the same data type;
otherwise false 
e.g.
     var sVal = "this";  
     var sVal2 = new String("this");  
     if (sVal === sVal2) // not true  
3.Inequality != True if operands are not the same; otherwise false 
e.g.
     var sVal = "this";  
     if (sVal == "that") // true  
4.Strict inequality !== True if operands are not the same, or are not the same  data type; otherwise false  
e.g.
     var sVal = "this";  
     var sVal2 = new String("this");  
     if (sVal !== sVal2) // true  
5.String method: localeCompare.  
     The localeCompare method takes one parameter, a string, which is compared against  the string value to which it is attached. The method returns a numeric value equal to  0 if the two strings are the same; –1 if the string parameter is lexically greater than the  original string; 1 otherwise:  
     var fruit1 = "apple";  
     var fruit2 = "grape";  
     var i = fruit1.localeCompare(fruit2); // returns -1 
 
 
Test Code:

window. { 

var sVal = "this"; 
var sVal2 = new String("this"); 
//if (sVal === sVal2) 
alert("sVal == sVal2:"+(sVal == sVal2));   
alert("sVal === sVal2:"+(sVal === sVal2));   
alert("sVal != sVal2:"+(sVal != sVal2)); 
alert("sVal !== sVal2:"+(sVal !== sVal2)); 
alert("sVal.localeCompare(sVal2):"+sVal.localeCompare(sVal2)); 

}
ide

相關文章
相關標籤/搜索