Skip to content

不正确 Comparison 运算符

快速摘要

你 used 错误 comparison 运算符, 所以边界值 是包含 or 排除当 它应该不 是.

为什么发生

  • Using > 当你 需要 >= (or vice versa)

  • Using < 当你 需要 <= (or vice versa)

  • Confusing 方向的 comparison

最小示例

✗ 错误代码
function canVote(age) {
  return age > 18; // 18-year-olds cannot vote!
}
console.log(canVote(18)); // false — should be true
✓ 修复代码
function canVote(age) {
  return age >= 18; // 18-year-olds can vote
}
console.log(canVote(18)); // true

Using > 18 排除 18-year-olds, 谁应该是 able 到 vote. 更改到 >= 18 包含边界值, giving 正确 result.

如何诊断

  • 测试精确边界值 到 see 如果它 是 handled 正确地

  • Print 条件 result for 边界值

  • Review comparison 运算符针对 intended logic

如何修复

  • 更改 > 到 >= or < 到 <= as 需要

  • 测试使用边界值 到验证 fix

  • 添加 comments 解释 intended 边界 behavior

如何预防

  • 总是测试边界值 in 单元测试

  • Think carefully 关于 whether 边界应该是 inclusive or exclusive

相关资源

相关术语

相关课程

  • 条件

    学习关于 comparison 运算符.

← 返回语言