0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【JS】if文の値を変数に代入する方法

Last updated at Posted at 2020-10-29

超基本的なことですが、ハマったので念のためメモ。

結論、条件分岐を使って変数に入る値を指定したい場合は、変数の定義とif文は別々に記述する

一つの式でやろうとするとできない、、

##条件分岐による代入方法

i = 10
result = 0

if (i == 10){
    result = i
}

console.log(result)

//出力
10

##NG事例

▼直接ifを書く

NG
i = 10
result = 0

result = {
    if (i == 10){
        result = i
    }
}

//出力
Uncaught SyntaxError: Unexpected token '=='

そもそもif文が使えない、、


▼関数で結果を入れようとする

NG
i = 10
result = 0

result = () => {
    if (i == 10){
        result = i
    }
}

console.log(result)

//出力
() => {
    if (i == 10){
        result = i
    }
}

関数がそのまま入ってしまう。

0
1
1

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?