Javascript IF(声纳误报?)

Javascript IFs (sonar false positive?)

我刚刚在 SonarQube 中发现了一个误导性问题, 我们有如下代码 (JS)

{…}
function test(searchQuery, role) {

console.log("inputs: " +searchQuery + ", " + role );
    if (!searchQuery && role) {
        console.log("first");
    }
    if (searchQuery && !role) {
        console.log("sec");
    }
    if (searchQuery && role) {
        console.log("3");
    }
    console.log("END");
}
{…}

并且 Sonarqube (6.7.4) 将最后一个 If 标记为评论的问题,应该修复它以避免每次出现 true (在第一个 IFs 中有一个 return 实际上,我修改了代码以进行测试)

使用测试值,输出为:

inputs: aaa, fff
test.txt.html:14 3
test.txt.html:16 END
test.txt.html:6 inputs: null, fff
test.txt.html:8 first
test.txt.html:16 END
test.txt.html:6 inputs: null, null
test.txt.html:16 END

我不是 javascript 专家,只是觉得有趣,有人知道吗,if there is any reason why the last if should be everytime true? 因为我不这么认为,reg。测试数据。

If you will place returns into first two IFs to be in place, then the code will continue in two cases: - if both variables are set, or if both are null, but if (null, null) should return undefined, not?

感谢任何澄清

如果您提供实际分析过的代码以及您在 SonarQube 中遇到的确切问题,那么帮助您会更容易。我无法重现您发布的代码的任何问题,但我可以在每个 if 块中重现一个带有 return 语句的问题(基于您消息末尾的注释)。

function test(searchQuery, role) {
    if (!searchQuery && role) {
        return;
    }
    if (searchQuery && !role) {
        return;
    }
    if (searchQuery && role) {
        return;
    }
}

SonarQube 然后在第三个 if 语句的条件中突出显示 role 并引发以下问题: 重构此代码,使此表达式的计算结果不总是为真。

searchQuery为真,role为假时,第二条if语句的条件为真,执行第二条return语句。 这意味着当 searchQuery 在第三个 if 语句的条件下为真时, role 不能为假。换句话说,role 可以从第三个 if 语句的条件中删除而不影响行为。