LoginSignup
0
0

More than 5 years have passed since last update.

メモ:javascriptの単項プラス(+)について

Last updated at Posted at 2019-01-23

javascsriptで文字列(string)から数値(number)への変換を行う時、parseInt()を使うが、javascriptの使用には以下のような記法も存在する。

const num1 = parseInt('5')
const num2 = +'5'

ブラウザのコンソールなどで試して見るとわかるがこれは同じ結果になる。
とはいえ、これは別にparseIntの省略形とかそういうわけではなく、仕様上はECMAscriptのUnary + Operator(単項プラス演算子)である。

ECMAScript Language Specification - ECMA-262 Edition 5.1

11.4.6 Unary + Operator

The unary + operator converts its operand to Number type.

The production UnaryExpression : + UnaryExpression is evaluated as follows:

1. Let expr be the result of evaluating UnaryExpression.
2. Return ToNumber(GetValue(expr)).

実装上はparseInt()の代わりなどで使われることが多そうだが、明示的ではなくぱっと見『???』と思ってしまうので、可読性がいいともいえないだろう。parseInt()が使われる頻度を考えれば、単項プラスにしたところでコード全体で見れば対して効率がよくなっているとも思えない。
高速であると言われている(が、自分で計測はしてないのでなんとも)。だが、高速とはいっても、numberへの変換だけを数百数千とやるようなコードをjavascriptで書くことがそうそうある気もしない(あるなら話は別なのだろうが。。)。

正直、あまり使わない方がいいのではないか、とも思えるが一応メモ。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0