简体   繁体   English

为什么我的 `if(result !== "false")` 返回 true?

[英]Why does my `if(result !== "false")` return true?

I make an ajax call to fetch data.我进行了 ajax 调用来获取数据。 If it exists, eg the result is set I´d like to run another function.如果它存在,例如结果设置我想运行另一个函数。

JS JS

success: function(result){ console.debug(result); console.log(result);
    if(result !== "false" || result !== ""){
        console.log('passed');    
    }

In console I have except "Passed".在控制台中,我除了“通过”。

The result is empty, but still my if statement evaluates to true.结果为空,但我的 if 语句仍为真。 Why?为什么?

This is what I send as result.这就是我发送的结果。 And it´s empty...而且是空的...

PHP PHP

$row = $stmt->fetch();
echo $row['objekt_nr'];

If the result is "false" then it is NOT an empty string, and the right hand side of the OR is true.如果结果为"false"则它不是空字符串,并且 OR 的右侧为真。

If the result is "" then it is NOT "false" and the left hand side of the OR is true.如果结果为""则它不是"false" ,OR 的左侧为真。

If it is anything else, then both sides of the OR statement are true.如果是别的,那么 OR 语句的两边都是真的。

Either way, the OR statement is true.无论哪种方式,OR 语句都是正确的。

You want an AND not an OR.你想要一个 AND 而不是 OR。

The conditional result !== "false" || result !== ""条件result !== "false" || result !== "" result !== "false" || result !== "" will always evaluate true since result can, at best, be one of the two values. result !== "false" || result !== ""将始终评估为真,因为 result 充其量只能是两个值之一。 In order for the conditional to be false, it result would have to be both "" and "false" at the same time!为了使条件为假, result必须同时为"""false"

For example:例如:

  • if result === "false" then result !== "" must be true (as result is "false" , not "" )如果result === "false" then result !== ""必须为真(因为 result 是"false" ,而不是""

  • if result === "" then result !== "false" must be true (as result is "" , not "false" ) if result === "" then result !== "false"必须为真(因为结果是"" ,而不是"false"

  • if result is neither "" nor "false" , then both sides are true, evaluating to true.如果 result 既不是""也不是"false" ,则双方都为真,评估为真。

What are you actually trying to check for?你究竟想检查什么?

if(result !== "false" && result !== "") would be true if result is neither "false" nor "" if(result !== "false" && result !== "")如果 result既不是"false"也不是""则为真

if(result === "false" || result === "") would be true if result is either "false" or "" if(result === "false" || result === "")如果结果为是真"false"""

Your ||你的 || needs to be an &&.必须是&&。

The statement if (result !== "false" || result !== "") will always be true! if (result !== "false" || result !== "")语句永远为真! The result string can never both "false" and "" at the same time... which is the only way the statement could ever resolve to false.结果字符串永远不能同时出现"false""" ……这是语句可以解析为false的唯一方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM