if语句
if(true){
alert("Greater than 25;");}
else{
alert("less than or equal to 25;");}
循环语句
do-while循环
do{
alert(i);
}while(i<10);
while循环
while(i<10)
{alert(i);}
for循环
for(var i=0;i<10;i++)
{
i+=2;
}
for-in语句
for-in语句是一种精确的迭代语句,可以用来枚举对象的属性。
for(var propName in window)
{
document.write(propName);
}
ECMAScript对象的属性没有顺序,所以通过for-in循环输出的属性顺序是不可以预测的。具体来说,所有的属性都会被返回一次,但返回的次序因浏览器而异。如果要迭代的对象是null和undefined,会不执行循环体。
label语句
用label语句可以在代码中添加标签。
start:for(var i=0;i<10;i++)
{alert(i);}
break语句和continue语句
break语句会立即退出循环,强制继续执行循环后面的语句。而continue语句虽然也是立即退出循环,但退出循环后会从循环开始的顶部继续执行。
var num =0;
outmost:
for (var i=0;i<10;i++){
for(var j=0;j<10;j++){
if(i==5 && j==5)
{break outmost;}
num++;
}
}
alert(num);//55
每个循环正常执行10次,num++语句执行100次,当i=5,j=5时,跳出整个循环,执行循环体之后的语句,共运行55次。
var num =0;
outmost:
for (var i=0;i<10;i++){
for(var j=0;j<10;j++){
if(i==5 && j==5)
{continue outmost;}
num++;
}
}
alert(num);//95
运行到i=5,j=5时,跳出outmost函数,从函数顶部开始运行,跳过了5次循环,共运行95次。
switch语句
switch(i){
case 1:
alert("1");
break;
case 2:
alert("2");
break;
case 3:
alert("3");
break;
default:
alert("0");
break;
}
输入1,输出1;输入2,输出2;输入0,输出0;
switch(i){
case 1:
alert("1");
case 2:
alert("2");
case 3:
alert("3");
default:
alert("0");
}
输入1,输出123;输入2,输出23。
switch(i){
case 1:
case 2:
alert("2");
break;
case 3:
alert("3");
break;
default:
alert("0");
break;
}
输入1,2都输出2。
try-catch语句
try{
try{
throw new Error("opps");
}
finally{
console.log("finally");
}
}
catch(ex){
console.error("outer",ex.message);
}//运行结果"finally" "outer""opps"
内层try抛出error后,寻找最近的catch语句,就要跳出本层try,跳出之前,先要运行finally,所以先输出finally,再输出”outer”“opps”。
try{
try{
throw new Error("opps");
}
catch(ex){
console.error("inner",ex.message);
finally{
console.log("finally");
}
}
catch(ex){
console.error("outer",ex.message);}
//运行结果"inner""opps" "finally"
try抛出异常,catch输出”inner”“opps”,之后运行finally,输出finally。
try{
try{
throw new Error("opps");
}
catch(ex){
console.error("inner",ex.message);
throw ex;
finally{
console.log("finally");
}
}
catch(ex){
console.error("outer",ex.message);}
//运行结果"inner""opps" "finally" "outer""opps"
try抛出异常,catch输出”inner”“opps” ,catch又抛出异常,最近一次catch是外层循环,匹配catch需要跳出本次循环,跳出之前先执行finally,输出”finally”,之后输出catch语句”outer”“opps”。