JavaScript-即使不满足条件也返回true [英] JavaScript - returning true even though condition is not fulfilled
问题描述
我有以下代码:
console.log(usernameExists);
if (usernameExists = true) {
console.log("returning true");
return true;
} else if (looped = true) {
console.log(usernameExists+" is returned");
looped = null;
return false;
}
第一个console.log(usernameExists)
返回的是false,但仍然收到控制台消息"returning true",而其中的函数返回的是true!我根本无法弄清楚.
条件始终为true
,因为您将此值分配给变量,并且该值是为if
子句评估的值.>
但是您可以使用不带比较值(且不分配此值)的直接检查.
除此之外,您可以将else
部分更改为仅if
部分,因为使用return
退出了该功能,因此在这种情况下不再发生else
.
if (usernameExists) {
console.log("returning true");
return true;
}
if (looped) {
console.log(usernameExists+" is returned");
looped = null;
return false;
}
I have the following code:
console.log(usernameExists);
if (usernameExists = true) {
console.log("returning true");
return true;
} else if (looped = true) {
console.log(usernameExists+" is returned");
looped = null;
return false;
}
The first console.log(usernameExists)
is returning false, but still I am getting a console message of "returning true", and the function in which this is, is returning true! I simply can't figure this out.
The condition is always true
, because you assign this value to the variable and this is the value which is evaluated for the if
clause.
But you could use a direct check without a compare value (and without assigning this value).
Beside that, you could change the else
part to only an if
part, becaue you exit the function with return
, so no more else
happen in this case.
if (usernameExists) {
console.log("returning true");
return true;
}
if (looped) {
console.log(usernameExists+" is returned");
looped = null;
return false;
}
这篇关于JavaScript-即使不满足条件也返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!