一元加(+)

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

一元加+)运算符在其操作数之前并计算其操作数,但会尝试将其转换为数字,如果它还不是的话。

尝试一下

const x = 1;
const y = -1;

console.log(+x);
// Expected output: 1

console.log(+y);
// Expected output: -1

console.log(+"");
// Expected output: 0

console.log(+true);
// Expected output: 1

console.log(+false);
// Expected output: 0

console.log(+"hello");
// Expected output: NaN

语法

js
+x

描述

虽然一元减(-)也可以转换非数字,但一元加是将某些东西转换为数字的最快和首选方法,因为它不对数字执行任何其他操作。它可以转换整数和浮点数的字符串表示形式,以及非字符串值 truefalsenull。支持十进制和十六进制(以 0x 为前缀)格式的整数。支持负数(但不适用于十六进制)。对 BigInt 值使用该运算符会引发 TypeError。如果它无法解析特定值,它将计算为 NaN

示例

数字用法

js
const x = 1;
const y = -1;

console.log(+x);
// 1
console.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® 2025 Language Specification
# sec-unary-plus-operator

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
Unary plus (+)

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见