24h購物| | PChome| 登入
2012-04-22 19:03:04| 人氣397| 回應0 | 上一篇 | 下一篇

[JavaScript] Conditionals in JavaScript

推薦 0 收藏 0 轉貼0 訂閱站台

If else statements

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

//Line 10 starts an if statement
//Nested in this if statement is an if else statement on lines 11 - 15
//This nested if else statement allows us to check another condition
//We close the first if statement at the start of line 16

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.";
}


Using if else statements in functions

// Define the function under this line
var canIDrive = function(myAge, legalDrivingAge) {
    if(myAge >= legalDrivingAge)
        return true;
    return false;
}

// Declare legalDrivingAge under myAge
var myAge = prompt("How old are you?");

//Create an if else statement using the function as a condition
if (canIDrive(myAge, 18)) {
  console.log("You can legally drive!");
}
else {
  console.log("You'll have to wait a few more years!");
}


Introducing the Switch statement

var born = prompt("What country were you born in?");
var result;

// write the whole switch statement
switch(born) {
    case "USA":
        result = 1;
        break;
    case "England":
        result = 2;
        break;
    default:
        result = 3;
}


Ternary operators

var food = prompt("Food?");
var foodType;
if (food === "taco") {
  foodType = "Mexican";
} else {
  foodType = "other"; 
}

//Re-write the above code using a ternary operator
foodType = (food === "taco") ? "Mexican" : "other";


台長: Morris
人氣(397) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: [學習]JavaScript |
此分類下一篇:[JavaScript] Introduction to Objects I
此分類上一篇:[JavaScript] Understanding parameters

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文