此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
一元加(+)
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
一元加(+)运算符在其操作数之前并计算其操作数,但会尝试将其转换为数字,如果它还不是的话。
In this article
尝试一下
const x = 1;const y = -1;console.log(+x);// Expected output: 1console.log(+y);// Expected output: -1console.log(+"");// Expected output: 0console.log(+true);// Expected output: 1console.log(+false);// Expected output: 0console.log(+"hello");// Expected output: NaN语法
js
+x描述
虽然一元减(-)也可以转换非数字,但一元加是将某些东西转换为数字的最快和首选方法,因为它不对数字执行任何其他操作。它可以转换整数和浮点数的字符串表示形式,以及非字符串值true、false 和null。支持十进制和十六进制(以0x 为前缀)格式的整数。支持负数(但不适用于十六进制)。对 BigInt 值使用该运算符会引发 TypeError。如果它无法解析特定值,它将计算为NaN。
示例
>数字用法
js
const x = 1;const y = -1;console.log(+x);// 1console.log(+y);// -1非数字用法
js
+true // 1+false // 0+null // 0+function (val) { return val; } // NaN+1n // throws TypeError: Cannot convert BigInt value to number规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-unary-plus-operator> |