我正在尝试检查字符串是否为空、小于或等于 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
. Why?
=
始终是作业。相等比较是==
(松散,强制类型尝试进行匹配)或===
(无类型强制)。
所以你要
if (str === ''){
// -----^^^
not
// NOT THIS
if (str = ''){
// -----^
当你这样做时会发生什么if (str = '')
那是任务 str = ''
完成,然后得到结果值(''
)被测试,有效地像这样(如果我们忽略一些细节):
str = '';
if (str) {
Since ''
is a falsyJavaScript 中的值,该检查将为 false 并且它会转到else if (str.length <= 9)
步。从那时起,str.length
is 0
,这就是代码所采用的路径。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)