2024-05-31|閱讀時間 ‧ 約 27 分鐘

Javascript入門-Day6:流程控制

if, else if, else

ifelse ifelse 用於根據條件執行不同的代碼塊。

let num = 10;

if (num > 10) {
console.log('Greater than 10');
} else if (num === 10) {
console.log('Equal to 10');
} else {
console.log('Less than 10');
}

三元運算子

三元運算子 (? :) 是一種簡潔的條件運算,根據條件表達式的真假來返回不同的值。

let num = 10;
let result = (num > 10) ? 'Greater than 10' : 'Not greater than 10';
console.log(result); // 'Not greater than 10'

switch語句

switch 語句用於根據不同的條件執行不同的代碼塊。

let fruit = 'apple';

switch (fruit) {
case 'apple':
console.log('This is an apple');
break;
case 'banana':
console.log('This is a banana');
break;
default:
console.log('Unknown fruit');
}

for迴圈

JavaScript 中的 for 迴圈有多種寫法,根據不同的需求可以選擇適當的變體。以下是常見的 for 迴圈寫法:

基本 for 迴圈

用於已知迭代次數的情況。

for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}

for...of 迴圈

用於遍歷可迭代對象(如陣列、字符串、MapSet 等)。

let array = [1, 2, 3, 4, 5];
for (let element of array) {
console.log(element); // 1, 2, 3, 4, 5
}

let str = "hello";
for (let char of str) {
console.log(char); // 'h', 'e', 'l', 'l', 'o'
}

for...in 迴圈

用於遍歷物件的可枚舉屬性,但不建議用於遍歷陣列。

let obj = { a: 1, b: 2, c: 3 };
for (let key in obj) {
console.log(key + ': ' + obj[key]); // 'a: 1', 'b: 2', 'c: 3'
}

forEach 方法

用於遍歷陣列中的每個元素,適合處理陣列時使用。

let array = [1, 2, 3, 4, 5];
array.forEach(function(element) {
console.log(element); // 1, 2, 3, 4, 5
});

// 使用箭頭函數
array.forEach(element => console.log(element));

while迴圈

while 迴圈在條件為真時重複執行代碼塊。

let i = 0;
while (i < 5) {
console.log(i); // 0, 1, 2, 3, 4
i++;
}

循環嵌套

循環嵌套是指在一個循環內部嵌套另一個循環。

for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
console.log(`i = ${i}, j = ${j}`);
}
}

控制迴圈語句

break

break 用於立即退出迴圈。

for (let i = 0; i < 10; i++) {
if (i === 5) {
break;
}
console.log(i); // 0, 1, 2, 3, 4
}

continue

continue 用於跳過本次迴圈迭代,進入下一次迭代。

for (let i = 0; i < 10; i++) {
if (i === 5) {
continue;
}
console.log(i); // 0, 1, 2, 3, 4, 6, 7, 8, 9
}

label

label 用於標記循環,以便在多層循環中使用 breakcontinue 跳出指定循環。

outerLoop:
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break outerLoop;
}
console.log(`i = ${i}, j = ${j}`);
}
}

這些是 JavaScript 中常見的條件語句和循環結構,掌握它們有助於編寫靈活且高效的代碼。

分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.