为什么我使用 = (单个等于)的相等比较不能正常工作?

IT技术 javascript equality
2021-02-06 19:00:13

我正在尝试检查字符串是否为空、小于或等于 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为什么?

1个回答

=总是赋值。相等比较是==(松散的,===强制类型尝试进行匹配)或(无类型强制)。

所以你要

if (str === ''){
// -----^^^

不是

// NOT THIS
if (str = ''){
// -----^

什么时候你做的情况if (str = '')是,转让 str = ''完成后,然后将得到的值('')进行测试,有效像这样(如果我们忽略了几个细节):

str = '';
if (str) {

由于''JavaScript 中值,该检查将是假的,并进入该else if (str.length <= 9)步骤。从那时起,str.lengthis 0,这就是代码所采用的路径。