CodeQL 文档

无用的条件

ID: js/trivial-conditional
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - correctness
   - external/cwe/cwe-570
   - external/cwe/cwe-571
Query suites:
   - javascript-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

如果条件始终计算为真或始终计算为假,这通常表示代码不完整或潜在的错误,应仔细检查。

建议

检查周围的代码以确定为什么条件是无用的。如果不再需要,请将其删除。

示例

以下示例构建一个数组 lines,然后尝试通过 if 条件 if (!lines) 检查它是否包含任何元素。

function getLastLine(input) {
  var lines = [], nextLine;
  while ((nextLine = readNextLine(input)))
    lines.push(nextLine);
  if (!lines)
    throw new Error("No lines!");
  return lines[lines.length-1];
}

请注意,在 JavaScript 中(与其他一些语言不同),数组和对象在布尔上下文中评估时始终被认为是真值。代码应该改为检查 lines.length

function getLastLine(input) {
  var lines = [], nextLine;
  while ((nextLine = readNextLine(input)))
    lines.push(nextLine);
  if (!lines.length)
    throw new Error("No lines!");
  return lines[lines.length-1];
}

参考

  • ©GitHub, Inc.
  • 条款
  • 隐私