Skip to content

字符串 Concatenation 相反 的 Addition

快速摘要

You used + with a string and a number, so JavaScript concatenated them (e.g., "10" + 5 = "105") instead of adding.

为什么发生

  • One operand 是 字符串, causing + 到 concatenate 相反 的 添加

  • 用户 输入 (哪个 是 总是 字符串) 是 不 converted 到 数字

  • JSON or 表单 数据 returned 字符串 相反 的 数字

最小示例

✗ 错误代码
let a = "10";
let b = 5;
console.log(a + b); // "105" — concatenation!
✓ 修复代码
let a = "10";
let b = 5;
console.log(Number(a) + b); // 15 — addition

When one operand is a string, + concatenates. "10" + 5 gives "105". Converting a to a number with Number() makes + perform addition: 10 + 5 = 15.

如何诊断

  • 检查 类型 的 两者都 operands 使用 typeof

  • Look for quotes 围绕 值 那个 应该 是 数字

  • Print result 到 see 如果 它 是 字符串 相反 的 数字

如何修复

  • Convert 字符串 到 数字 使用 数字(), parseInt(), or unary +

  • Use template literals for intentional 字符串 concatenation

  • 验证 and convert 用户 输入 之前 arithmetic

如何预防

  • 总是 convert 用户 输入 到 数字 之前 arithmetic

  • Use TypeScript 到 enforce numeric 类型

相关资源

相关术语

相关课程

← 返回语言