天天看点

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]

继续阅读