JavaScript条件句_CONDITIONAL STATEMENTS

let sale = true
if(sale){
  console.log('Time to buy!')
}

If...Else

let sale = true
sale = false
if(sale) {
  console.log('Time to buy!')
}
else{
  console.log('Time to wait for a sale.')
}

Comparison Operators

let hungerLevel = 7
if(hungerLevel>7){
  console.log('Time to eat!')
}
else{
  console.log('We can eat later!')
}

Logical Operators

  • theandoperator (&&)
  • theoroperator (||)
  • the notoperator, otherwise known as the_bang_operator (!)
let mood = 'sleepy';
let tirednessLevel = 6;

if((mood === 'sleepy') &&(tirednessLevel >8)){
  console.log('time to sleep')
}
else{
  console.log('not bed time yet')
}

Truthy and Falsy

考虑non-boolean data types

表示错误的有

  • 0
  • Empty strings like "" or'' 空字符串
  • nullwhich represent when there is no value at all
  • undefinedwhich represent when a declared variable lacks a value 未定义变量
  • NaN, or Not a Number

Truthy and Falsy Assignment

||or statements check the left-hand condition first

所以这两个是等价的

let  defaultName
if  (username)  { 
defaultName  =  username
} 
else  {
defaultName  =  'Stranger'
}
let  defaultName  =  username  ||  'Stranger';
let tool = 'marker';
let writingUtensil = tool ||'pen'
console.log(`The ${writingUtensil} is mightier than the  sword.`);
The pen is mightier than the sword.
let tool = '';
let writingUtensil = tool ||'pen'
console.log(`The ${writingUtensil} is mightier than the sword.`);
The marker is mightier than the sword.

Ternary Operator

三元运算符

isNightTime  ?  console.log('Turn on the lights!')  :  console.log('Turn off the lights!');
  • 条件在?前面
  • ?后面有两个待执行语句,用:隔开
  • 如果条件为真,执行第一个语句(:前面的),为假执行第二个(:后面的)

Else If Statements

let stopLight = 'yellow'
if (stopLight === 'red'){ 
console.log('Stop!')
} 
else if (stopLight === 'yellow'){ 
console.log('Slow down.')
} 
else if (stopLight === 'green'){
console.log('Go!'); 
}  
else{  
console.log('Caution, unknown!')
}

The switch keyword

let athleteFinalPosition = 'first place';

switch(athleteFinalPosition){
       case (athleteFinalPosition === 'first place'):
       console.log('You get the gold medal!')
       break
    case (athleteFinalPosition === 'second place'):
       console.log('You get the silver medal!')
       break
    case (athleteFinalPosition === 'third place'):
       console.log('You get the bronze medal!')
       break
    default:
    console.log('No medal awarded.')
    break
       }

你可能感兴趣的:(javascript)