提问人:Sam 提问时间:7/8/2016 最后编辑:T.J. CrowderSam 更新时间:7/8/2016 访问量:434
为什么我使用 =(单个等于)的等式比较不能正常工作?[复制]
Why doesn't my equality comparison using = (a single equals) work correctly? [duplicate]
问:
我正在尝试检查字符串是否为空、小于或等于 9 位数字或最多 10 位数字。但它始终遵循 .else if (str.length <= 9)
if (str = ''){
console.log("The string cannot be blank");
} else if (str.length <= 9) {
console.log("The string must be at least 9 characters long");
} else if (str.length <= 10) {
console.log("The string is long enough.");
}
无论我投入什么,我总是得到.为什么?The string must be at least 9 characters long
答:
7赞
3 revsT.J. Crowder
#1
=
始终是赋值。相等比较是(松散的、强制类型以尝试进行匹配)或(无类型强制)。==
===
所以你想要
if (str === ''){
// -----^^^
不
// NOT THIS
if (str = ''){
// -----^
当你这样做时,会发生什么,即赋值完成,然后测试结果值 (),有效地像这样(如果我们忽略几个细节):if (str = '')
str = ''
''
str = '';
if (str) {
由于 JavaScript 中是一个虚假值,因此该检查将为 false,并进入该步骤。因为在这一点上,是 ,这就是代码所采用的路径。''
else if (str.length <= 9)
str.length
0
评论