How to compare string equality in JavaScript: 1. Use the "==" operator for equality comparison, syntax "str1==str2"; 2. Use the "===" operator for equality comparison, Syntax "str1===str2".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
javascript compares strings for equality
Method 1: Use "==
" for equality comparison :
var str1 = "123456" ; // 字符串 var str2 = "123456" ; // 字符串 alert(str1==str2) ; // 打印出 true,即相等
Method 2: Use "===" for equality comparison
var str1 = "123456" ; // 字符串 var str2 = "123456" ; // 字符串 alert(str1===str2) ; // 打印出 true,即相等
Expand knowledge: "==" and "== The difference between ="
"==" means "equal", and the necessary value type conversion will be performed before equality comparison is performed. To put it simply, the value is converted to the same type first and then compared for equality. Even if the types of the compared values are different, they can be cast to the same type without causing an error.
var str1 = 123456 ; // 整型 var str2 = "123456" ; // 字符串 alert(str1==str2) ; // 打印出 true,即相等
"===" means "identity" and no type conversion will be performed, so if the two values are not of the same type, then when compared, it will return false. If you compare two variables whose types are incompatible with each other, a compilation error will occur.
var str1 = 123456 ; // 整型 var str2 = "123456" ; // 字符串 alert(str1===str2) ; // 打印出 false,即不相等
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to compare strings for equality in javascript. For more information, please follow other related articles on the PHP Chinese website!