悬挂 'else' 的误导性缩进¶
ID: js/misleading-indentation-of-dangling-else
Kind: problem
Security severity:
Severity: warning
Precision: very-high
Tags:
- readability
- statistical
- non-attributable
- external/cwe/cwe-483
Query suites:
- javascript-security-and-quality.qls
在 JavaScript 中,else
子句始终与最近的先前 if
语句相关联,该语句还没有 else
子句。最佳实践是使用缩进来通过相同数量的空白缩进匹配的 if
… else
对来明确此结构。
将嵌套 if
语句的 else
子句缩进,以暗示它与外部 if
语句匹配(而不是它实际所属的语句),这会让读者感到困惑,甚至可能表明程序逻辑中存在错误。
建议¶
确保匹配的 if
… else
对已相应缩进。
示例¶
在以下示例中,第 5 行的 else
属于第 3 行的 if
,而它的缩进错误地暗示它属于第 2 行的 if
。
function f() {
if (cond1())
if (cond2())
return 23;
else
return 42;
return 56;
}
要更正此问题,请将第 5 行的 else
进一步缩进。
function f() {
if (cond1())
if (cond2())
return 23;
else
return 42;
return 56;
}
始终将 if
语句的分支括在花括号中,也可以避免对哪个 if
属于哪个 else
的混淆。
function f() {
if (cond1()) {
if (cond2()) {
return 23;
} else {
return 42;
}
}
return 56;
}