Js流程控制

流程控制php

 

流程控制的分類、;html

順序結構   分支結構   循環結構dom

 

順序結構:程序默認的自上而下的執行過程就是順序結構~ide

分支結構:spa

單項分支htm

格式1:對象

If(條件表達式){ip

Js語句內存

}字符串

 

格式2:

If(條件表達式)  JS語句

 

//單向分支 能夠使用{}也能夠不用

var mc='單身';

if(mc=='單身'){

alert('未婚');

}

 

有{}的單項分支 條件表達式的結構能夠影響多條語句,而沒有{}的單線分支只能影響表達式以後的第一條語句

雙項分支

格式1:

If(條件表達式){

多條JS語句

}else{

多條JS語句

}

 

格式2:

If(條件表達式)

1條JS語句

else

1條JS語句

 

多項分支

Switch..case 分支和php的一致

If..else if..else分支

Else if 不容許攜程elseif  中間必須有空格

//多向分支 switch case

//隨機產生1-5的數字 random--->0-1之間的數字 *5 Math.ceil()進一法取整

var num=Math.ceil(Math.random()*5);

switch(num){

case 1:

alert(111111111);

break;

default:

alert(5555555555);

break;

}

 

 

//if()else if

var num=Math.ceil(Math.random()*5);

if(num==1){

alert(1111111111);

}else if(num==4){

alert(4444444);

}else{

alert(5555555);

}

巢狀分支

巢狀分支就是單項分支和雙項分支等其餘if..else分支結構互相嵌套的結果

 

 

循環結構:

While循環  

do..while循環  

for循環  

for..in循環  專門用於遍歷對象成員的循環結構

 

格式:

 for(var 變量 in  對象){

能夠輸出對象的成員名或者值.

}

 

注意:因爲for..in循環使用的變量不是一個肯定的字符串名稱,因此不能使用對象.變量的方式,須要使用對象[變量]的方式才能正確的訪問到對象的指定成員值!

 

<!doctype html>

 

<script>

//while循環

document.write('<table border="1" width="800" align="center">');

var j=0;

while(j<10){

 

document.write('<tr>');

var i=0;

while(i<10){

document.write('<td>'+j+''+i+'</td>');

i++;

}

document.write('</tr>');

 

j++;

}

document.write('</table>');

document.write('<hr color="red">');

 

 

//do  while 循環

var num=1;

var total=0;

do{

total+=num;

num++;

}while(num<=100)

document.write(total);

document.write('<hr color="purple">');

 

//for循環

for(var i=1;i<=10;i++){

//console.log(i);

}

 

//for in 循環

alert(window);

for(var i in window){

console.log(i+'-----'+window[i]);

}

 

 

</script>

 

 

其餘結構:

With語法:  設定對象環境的語法結構

格式:

With(對象){

//JS代碼  此處使用指定對象的成員時,不須要指定對象名稱

}

注意: 該方式不推薦使用,內存處理有問題,會下降效率.

 

<!doctype html>

 

<script>

/*

console.log(location);

console.log(location.pathname);

console.log(location.href);

console.log(location.origin);

*/

 

with(location){

console.log(pathname);

console.log(href);

console.log(origin);

}

</script>

相關文章
相關標籤/搜索