严格相等比较
Strict equality comparison
我有联系表。我使用 js 进行表单字段验证:
if(email.length == 0 || email.indexOf('@') == '-1'){
var error = true;
}
但我想使用严格的相等比较以获得更好的性能。所以我尝试
if(email.length === 0 || email.indexOf('@') === '-1'){
var error = true;
}
但这行不通。
对于严格相等,值应该相等,类型也应该相同。根据您的代码,'-1'
是 string
类型,但 indexOf
return 是 number
类型。 === 运算符不进行转换,因此即使值相等但类型不同,=== 也只会 return false.
您可以尝试使用 typeof
运算符查找类型。
因此,如果您尝试 typeof '-1'
,它将 return "string" 和
typeof 'email.indexOf('@')
会 return "number"
因此,正确的做法是删除数字 -1 周围的引号,如下所示。
if(email.length === 0 || email.indexOf('@') === -1){
var error = true;
}
来自 MDN
Strict equality compares two values for equality. Neither value is
implicitly converted to some other value before being compared. If the
values have different types, the values are considered unequal.
Otherwise, if the values have the same type and are not numbers,
they're considered equal if they have the same value. Finally, if both
values are numbers, they're considered equal if they're both not NaN
and are the same value, or if one is +0 and one is -0.
Identity / Strict Equality (===
) Comparison Operator will not convert types. This is what separates it from regular equality. .indexOf()
将 return 一个数字,这(显然)与字符串 -1
不同。理论上,您可以将一个转换为另一个,但最好的方法是只包含数字,如下所示:
if (email.length == 0 || email.indexOf('@') == -1) {
... Your Code Here...
}
我有联系表。我使用 js 进行表单字段验证:
if(email.length == 0 || email.indexOf('@') == '-1'){
var error = true;
}
但我想使用严格的相等比较以获得更好的性能。所以我尝试
if(email.length === 0 || email.indexOf('@') === '-1'){
var error = true;
}
但这行不通。
对于严格相等,值应该相等,类型也应该相同。根据您的代码,'-1'
是 string
类型,但 indexOf
return 是 number
类型。 === 运算符不进行转换,因此即使值相等但类型不同,=== 也只会 return false.
您可以尝试使用 typeof
运算符查找类型。
因此,如果您尝试 typeof '-1'
,它将 return "string" 和
typeof 'email.indexOf('@')
会 return "number"
因此,正确的做法是删除数字 -1 周围的引号,如下所示。
if(email.length === 0 || email.indexOf('@') === -1){
var error = true;
}
来自 MDN
Strict equality compares two values for equality. Neither value is implicitly converted to some other value before being compared. If the values have different types, the values are considered unequal. Otherwise, if the values have the same type and are not numbers, they're considered equal if they have the same value. Finally, if both values are numbers, they're considered equal if they're both not NaN and are the same value, or if one is +0 and one is -0.
Identity / Strict Equality (===
) Comparison Operator will not convert types. This is what separates it from regular equality. .indexOf()
将 return 一个数字,这(显然)与字符串 -1
不同。理论上,您可以将一个转换为另一个,但最好的方法是只包含数字,如下所示:
if (email.length == 0 || email.indexOf('@') == -1) {
... Your Code Here...
}