JavaScript

Conditionals

30 May 2014

条件式

if else 文

if 文

var yourName = "";
var result = "";
if (yourName.length===0) {
  result = "What is your name?";
};

条件に合うもの、合わないもの

var yourName = "NIck";
var result =  "";

if (yourName.length > 0) {
   result = "Hi "+ yourName;
} else {
   result = "What is your name?";
};

複数の条件をテスト

var yourName = "take";
var gender = "female";
var result;

if (gender==="male") {
  result = "His name is "+yourName;
} else if (gender==="female") {
  result = "Her name is "+yourName;
} else {
  result = "Hi "+yourName;
};

1つの条件を満たす

var yourName = "Take";
var gender = "female";

// don't forget to use the || operator 
if (gender === "male" || gender === "female"   ) {
  result = true;
} else {
  result = false;
};

両方の条件を満たす

var yourName = "Take";
var gender = "male";
var result;

if (yourName.length>0 && gender.length > 0) {
  result = "Thanks";
} else {
  result = "Please make sure both yourName and gender are filled in.";
};

条件文の入れ子

var yourName = "Take";
var gender = "male";
var result;

if (yourName.length > 0 && gender.length > 0) {
  if (gender ==="male" || gender==="female") {
    result = "Thanks";
  } else {
    result = "Please enter male or female for gender.";
  }
} else {
  result = "Please tell us both your name and gender.";
};

switch 文

var jacketColor = "green";
var result;

switch (jacketColor) {
    
  case "black":
    result = "Pay $300";
    break;
    
  case "brown":
    result = "Pay $200";  
    break;
    
  case "green":
    result = "Pay $5";
    break;
    
  default:
    result = "This color does not match my eyes!";
};

Ternary operators

result = x > y ? "good job" : 20;

右辺の結果を左辺に代入する。

x > y ?

"good job" : 20;

条件式が

真の時 : の左側の値が result へ代入される

負の時 : の右側の値が result へ代入される

var x = 2;
var y = 3;

if (x > y) {
  result = "good job";
}
else {
  result = 20;
}

//上記を ternary operator で書くと
result = x > y ? "good job" : 20;