Phần 3: cấu trúc điều khiển và vòng lặp 2007-08-18 10:41:12

Phần này thì khá quen thuộc với hầu hết người lặp trình nên TG chỉ để những đọa code mô tả thôi.
IF
if (condition)
{
code to be executed if condition is true
}


if..else
if(condition1){
//code for condition1
}else if(condition2){
// code for condition 2
}else{
// code for not condition1 and not condition2
}


Switch:
switch(n)
{
case 1:
  execute code block 1
  break    
case 2:
  execute code block 2
  break
default:
  code to be executed if n is
  different from case 1 and 2
}


For:
for (var=startvalue;var<=endvalue;var=var+increment)
{
    code to be executed
}


For...in:
for (variable in object)
{
    code to be executed
}

Ví dụ:
<script type="text/javascript">
var x
var mycars = new Array()
mycars[0] = "Saab"
mycars[1] = "Volvo"
mycars[2] = "BMW"

for (x in mycars)
{
document.write(mycars[x] + "<br />")
}

// hoặc

for (var x in mycars)
{
document.write(mycars[x] + "<br />")
}
</script>


while:
while (var<=endvalue)
{
    code to be executed
}


break: ngắt vòng lặp và thực hiện tiếp những script phía sau vòng lặp
Ví dụ:
<script>
n = 0;
for(i=0;i<5;i++){
if(i==2) break;
n++;
document.write('value: '+ n +'<br />');
}
n = n +10;
document.write('Value: '+n);
</script>

Kết quả:
value: 1
value: 2
Value: 12

continue: bỏ qua bước lặp hiện tại và thực hiện bước lặp tiếp theo
Ví dụ:
<script>
n = 0;
for(i=0;i<5;i++){
if(i==2) continue;
n = i;
document.write('value: '+ n +'<br />');
}
n = n +10;
document.write('Value: '+n);
</script>

Kết quả:
value: 0
value: 1
value: 3
value: 4
Value: 14

with:
Ví dụ:
<script>
with (document)
{
   for (i in this)
   {
       write("Property = " + i + " Value = " + document[i] + "<BR>\n")
   }
}</script>

Kết quả:
Property = getInterface Value = undefined
Property = console Value = undefined
................

Tra loi 0 comment(s) TG 2007-08-18 10:41:12