0
0

More than 1 year has passed since last update.

javascript14_演算

Last updated at Posted at 2022-02-18

演算する時に、元の変数の値を変更しません。
image.png

数値じゃない値を計算する時に、該当数値をNumに変換します。

image.png
下記の書き方の方が頻繁的に使われます。
image.png

注意して欲しいケース:
result = 1 + 2 + "3";
console.log("result:" + result)
左から計算するため、結果は33です。

result = "1" + 2 + 3;
console.log("result:" + result)
結果は123です。

加算以外に、全て数値型の文字列は全てNumberに変換されます。
result = 100 - "2";
結果は98です。
result = 2 * "8";
結果は16です。
result = 2 * undefined;
結果はNaNです。
result = 2 * null;
結果は0です。

全ての値は- * /演算をする際にNumberに変換されます。
そのため、-0, *1, /1で値をNumberに変換できます。
例:
var d = "12";
d = d - 0;
console.log(typeof d);

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