JavaScript-即使不满足条件也返回true [英] JavaScript - returning true even though condition is not fulfilled

查看:83
本文介绍了JavaScript-即使不满足条件也返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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屋!

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