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.

JavaScript,10,switch文,case,default,break,初心者向け

Posted at

10,switch文
JSでのswitch文の書き方を解説しています。
case(ケース)、default(デフォルト)、break(ブレイク)のそれぞれの意味と実際のコーディング例も紹介しています。
if, else ifなどを多く使う場面においては重宝しますので、是非覚えていきましょう!

const weathers = ["晴れ", "曇り", "雨", "雪"],
  randomNumber = Math.floor(Math.random() * weathers.length),
  randomWeather = weathers[randomNumber];
  WeathersMessageElement = document.getElementById("WeathersMessage");

document.getElementById("weather").textContent = "今日の天気は" + randomWeather + "です";

↓ここから

if (randomWeather === "晴れ") {
WeathersMessageElement.textContent = "日傘を持って行った方がいいかも";
} else if (randomWeather === "曇り") {
  WeathersMessageElement.textContent = "今日は一日曇っているみたいです";
} else if (randomWeather === "雨") {
  WeathersMessageElement.textContent = "傘を持って行きましょう";
}else if (randomWeather === "雪") {
  WeathersMessageElement.textContent = "今日は寒そうなのでコートを着て行きましょう";
}

↑ここまではswitchできる

function insertTextWeatherMessage(text) {
  WeathersMessageElement.textContent =text;
}


switch (randomWeather) {
  case "晴れ":
    insertTextWeatherMessage = ("日傘を持って行った方がいいかも");
    break;
  case "曇り":
    insertTextWeatherMessage = ("今日は一日曇っているみたいです");
    break;
  case "雨":
    insertTextWeatherMessage = ("傘を持って行きましょう");
    break;
  case "雪":
    insertTextWeatherMessage = ("今日は寒そうなのでコートを着て行きましょう");
    break;
    default:
      insertTextWeatherMessage = ("今日はやばい");
}

randomWeather === 下のcaseのどれかになりなら実行される
default:はそれ以外

0
1
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
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?