天天看點

JS基礎文法3(if-else語句)

[b][size=large]1. if-else語句:單分支語句[/size][/b]

[size=large]a) 文法:[/size] if(條件表達式)

{

語句體1;

}

else

{

語句體2;

{

[size=large]b) 說明:[/size]

i. 條件表達式:

因為JS是弱類型的原因,其它類型的資料也可以作為條件表達式,執行時會按照類型轉換規則轉換為boolean類型後再判斷

ii. 語句體1:條件表達式為true時執行

iii. 語句體2:條件表達式為false時執行

iv. else:為可選項,如果條件表達式為false時沒有需要執行的代碼,則可以省略不寫

v. 大括号{}:如果語句體中隻有一行代碼時可以省略(不建議)

vi. 條件表達式如果是變量與數值(number)進行是否相等的比較,建議将數值寫在左邊,避免出現将==寫成=的錯誤

eg:

var a=0;

if[color=red](a==0)[/color]

{

console.debug(“yes”);

}

else

{

console.debug(“no”);

} [color=green]//結果為yes。a為number,a==0結果為true[/color]

var a=0;

if[color=red](a=0)[/color]

{

console.debug(“yes”);

}

else

{

console.debug(“no”);

} [color=green]//結果為no。a=0表示将0指派給a(number類型),number轉換成boolean型,則數字0轉換後為false[/color]

[size=large]c) 嵌套:[/size]

i. If或else的語句體中還可以嵌套if-else

ii. 如果else的語句體當中隻有if-else,可以寫成else if的形式

if(條件表達式1) if(條件表達式1)

{語句體1;} {語句體1;}

else 簡化為: else if(條件表達式2)

{ {語句體2;}

If(條件表達式2) else{語句體3;}

{語句體2;}

else{語句體3;}

{

[size=large]d) 深入條件表達式:[/size]

i. 多個條件時應盡量使用邏輯運算符,避免使用位運算符

ii. NaN參與的比較結果都是false

eg:

<script type="text/javascript">

var a=3,b,c;

c=a/0;

b=0/0;

if(c>b){console.debug("yes");}

else{console.debug("no");}

[color=green]//no[/color]

if(c<=b){console.debug("yes");}

else{console.debug("no");}

[color=green]//no(c>b時輸出結果為no,按正常則c<=b時為yes,但因為b為NaN,是以比較結果均為false,輸出結果為no)[/color]

console.debug("b:"+b);

[color=green]//b:NaN[/color]

console.debug("typeof b:"+typeof b);

[color=green]//typeof b:number[/color]

</script>

iii. 字元串與字元串可以使用比較運算:按照字元編碼(英文是ASCII,中文是Unicode)

iv. 字元串與數值比較,需要将字元串轉成數值才能比較,如果字元串中不全是數字則轉成NaN,比較結果一定是false

eg:

var a="tom";

var a1="tomm";

var b="tonny";

var c=10;

var d="2"

if(a>b)

{console.debug("yes");}

else

{console.debug("no");}

[color=green]//no [/color] [color=red](ASCII中n大于m)[/color]

if(a>a1)

{console.debug("yes");}

else

{console.debug("no");}

[color=green]//no[/color] [color=red](tomm比tom大)[/color]

if(a>c)

{console.debug("yes");}

else

{console.debug("no");}

[color=green] //no[/color] [color=red](a為string,c為number,a不全是數字,則結果為NaN) [/color]

if(c>d)

{console.debug("yes");}

else

{console.debug("no");}

[color=green]//yes[/color] [color=red](d雖為string類型,但可以轉換成number類型,再進行比較) [/color]

繼續閱讀