1. 程式人生 > 實用技巧 >JavaScript基本流程控制 if, switch, while, do while, for

JavaScript基本流程控制 if, switch, while, do while, for

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

</body>
<style>
    span{
        display: inline-block
; width: 20px; border: 1px solid black; } </style> <script> // If 語句 if(1){ console.log(1); }else{ console.log(0); } if(1){ console.log(1); }else if(1+1 == 3){ console.log(0); } // 三元表示式: 條件是否滿足?滿足輸出2,否則輸出5 let hd
= true ? 2:5; // switch let name = "ziwen"; switch(name){ case undefined: console.warn("undefined!"); case "": console.log('可能是以下值'); case 'zi': console.log('zi'); break; case 'ziwen': console.log(
'ziwen'); break; default: console.log("yes"); } // switch 替代 if switch(true){ case 1+1==2: console.warn("undefined!"); break; case 0: console.log('zi'); break; default: console.log("yes"); } // while, do while document.write( '<table border="1" width="100%">' ); let tr = 5; while (tr-- > 0) { document.write('<tr>'); let td = 3; do { document.write('<td>'+td+'</td>'); } while (--td > 0); document.write('</tr>'); } document.write( '</table>' ); // for 列印楊輝三角 for(let i = 0; i < 4; i++){ for (let j = 4 - i; j > 0; j--) { document.write("<span>*</span>"); } for (let k = 2 * i + 1; k > 0; k--) { document.write("<span>&</span>"); } document.write("<br>"); } // for-in for (const key in object) { if (object.hasOwnProperty(key)) { const element = object[key]; } } // for-of for (const iterator of object) { // 迴圈迭代物件:包括陣列,字串 } </script> </html>