LoginSignup
9
7

More than 5 years have passed since last update.

x++ と ++x の違い。x=10; y=2; console.log(x++ - (x * y))の値は?

Last updated at Posted at 2017-09-04

一瞬あれっ?ってなりました。

インクリメントとデクリメント

++はインクリメント演算子。
x++x += 1 は等しいです。

--はデクリメント演算子。
X--x -= 1 は等しいです。

前置インクリメント(デクリメント)

let x = 10;
let y = ++x;

console.log(x);    // 11
console.log(y);    // 11

x1 だけ加算されたあと、 y に代入されます。
デクリメントも同様の処理順です。

後置インクリメント(デクリメント)

let x = 10;
let y = x++;

console.log(x);    // 11
console.log(y);    // 10

yx の値が参照されたあと、 x に1が加算されます。
デクリメントも同様の処理順です。

x=10; y=2; console.log(x++ - (x * y))の値

答えは -12 となります。

x++ を参照する際に 10 を取得します。
その後、X11 になり、 x * y11 * 2 となります。
結果、計算式は 10 - 11 * 2 となります。

後置インクリメントを使うと値は -11 となります。

let x = 10;
let y = 2;
console.log(++x - x * y);    // -11

参考

ここまで読んでいただきありがとうございました。

9
7
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
9
7