Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. JavaScript
  3. JavaScript 参考
  4. 表达式和运算符
  5. 一元加(+)

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

一元加(+)

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月⁩.

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

尝试一下

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

描述

虽然一元减(-)也可以转换非数字,但一元加是将某些东西转换为数字的最快和首选方法,因为它不对数字执行任何其他操作。它可以转换整数和浮点数的字符串表示形式,以及非字符串值truefalsenull。支持十进制和十六进制(以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

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp