为什么我的等式比较使用=(单个等于)才能正常工作? [英] Why doesn't my equality comparison using = (a single equals) work correctly?

查看:109
本文介绍了为什么我的等式比较使用=(单个等于)才能正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查字符串是否为空,小于或等于9位数,或最多10位数。但它始终跟在 else if(str.length< = 9)

I'm trying to check if a string is blank, less than or equal to 9 digits, or up to 10 digits. But it always follows the 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.");
}

无论我投入什么,我总是得到字符串长度必须至少为9个字符。为什么?

No matter what I put in, I always get The string must be at least 9 characters long. Why?

推荐答案

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

= is always assignment. Equality comparison is == (loose, coerces types to try to make a match) or === (no type coercion).

所以你想要

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

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

当你执行 if(str ='')时会发生什么赋值 str =''已完成,然后是结果值('' )经过测试,实际上是这样的(如果我们忽略了一些细节):

What happens when you do if (str = '') is that the assignment str = '' is done, and then the resulting value ('') is tested, effectively like this (if we ignore a couple of details):

str = '';
if (str) {

由于''是JavaScript中的 falsy 值,该检查将为false,如果(str.length< = 9) else c>步骤。从那时起, str.length 0 ,这就是代码所采用的路径。

Since '' is a falsy value in JavaScript, that check will be false and it goes to the else if (str.length <= 9) step. Since at that point, str.length is 0, that's the path the code takes.

这篇关于为什么我的等式比较使用=(单个等于)才能正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆