加法(+)
加法 (+
) 运算符生成数字操作数或字符串连接的总和。
¥The addition (+
) operator produces the sum of numeric operands or string concatenation.
Try it
语法
描述
¥Description
+
运算符针对两个不同的操作进行了重载:数字加法和字符串连接。评估时,先 将两个操作数强制为原语。然后,测试两个操作数的类型:
¥The +
operator is overloaded for two distinct operations: numeric addition and string concatenation. When evaluating, it first coerces both operands to primitives. Then, the two operands' types are tested:
- 如果一侧是字符串,则另一个操作数也是 转换为字符串,并且它们被连接起来。
- 如果都是 BigInts,则进行 BigInt 加法。如果一侧是 BigInt 而另一侧不是,则抛出
TypeError
。 - 否则两边都是 转换为数字,进行数字相加。
字符串连接通常被认为与 模板文字 或 String.prototype.concat()
等效,但事实并非如此。加法将表达式强制为原语,优先调用 valueOf()
;另一方面,模板文字和 concat()
将表达式强制转换为字符串,该字符串优先调用 toString()
。如果表达式有 [Symbol.toPrimitive]()
方法,则字符串连接会使用 "default"
作为提示来调用它,而模板文字则使用 "string"
。这对于具有不同字符串和原始表示形式的对象非常重要,例如 颞,其 valueOf()
方法会抛出异常。
¥String concatenation is often thought to be equivalent with template literals or String.prototype.concat()
, but they are not. Addition coerces the expression to a primitive, which calls valueOf()
in priority; on the other hand, template literals and concat()
coerce the expression to a string, which calls toString()
in priority. If the expression has a [Symbol.toPrimitive]()
method, string concatenation calls it with "default"
as hint, while template literals use "string"
. This is important for objects that have different string and primitive representations — such as Temporal, whose valueOf()
method throws.
const t = Temporal.Now.instant();
"" + t; // Throws TypeError
`${t}`; // '2022-07-31T04:48:56.113918308Z'
"".concat(t); // '2022-07-31T04:48:56.113918308Z'
建议你不要使用 "" + x
来执行 字符串强制。
¥You are advised to not use "" + x
to perform string coercion.
示例
使用数字进行加法
使用 BigInts 进行加法
¥Addion using BigInts
1n + 2n; // 3n
你不能将 BigInt 和数字操作数混合在一起。
¥You cannot mix BigInt and number operands in addition.
1n + 2; // TypeError: Cannot mix BigInt and other types, use explicit conversions
2 + 1n; // TypeError: Cannot mix BigInt and other types, use explicit conversions
"1" + 2n; // TypeError: Cannot mix BigInt and other types, use explicit conversions
要使用 BigInt 和非 BigInt 进行加法,请转换任一操作数:
¥To do addition with a BigInt and a non-BigInt, convert either operand:
1n + BigInt(2); // 3n
Number(1n) + 2; // 3
使用字符串进行加法
规范
Specification |
---|
ECMAScript Language Specification # sec-addition-operator-plus |
浏览器兼容性
BCD tables only load in the browser