Skip to main content

ECMAScript 语句

在 ECMAScript 中,语句是一组代码指令,用于告诉计算机执行特定的操作。

条件语句

条件语句用于根据不同的条件执行不同的代码块。

if-else 语句

let hour = 12;

if (hour < 12) {
console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}

switch-case 语句

let day = 2;
let dayName;

switch (day) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
default:
dayName = "Unknown";
}
console.log(dayName);

循环语句

循环语句用于重复执行一段代码块,直到满足指定条件为止。

for 循环语句

for (let i = 0; i < 5; i++) {
console.log(i);
}

for 语句的执行顺序

  1. 定义初始值 let i = 0
  2. 判断循环成立条件
  3. 条件成立执行循环体中的内容
  4. 执行步长累加操作
  • break:强制结束整个循环
  • continue:结束本轮循环,执行下一轮循环
for (let i = 0; i < 5; i++) {
if (i === 3) {
break; // 循环在 i 等于 3 时终止
}
console.log(i);
}

for (let i = 0; i < 5; i++) {
if (i === 3) {
continue; // 循环在 i 等于 3 时跳过当前循环
}
console.log(i);
}

while 循环语句

let count = 0;
while (count < 5) {
console.log(count);
count++;
}

do-while 循环语句

let num = 0;
do {
console.log(num);
num++;
} while (num < 5);

for in 循环语句

用于遍历对象的属性。

const person = {
name: 'Alice',
age: 18,
job: 'engineer'
};

for (const key in person) {
console.log(`${key}: ${person[key]}`);
}

for of 循环语句

用于遍历可迭代对象的元素,如数组、字符串、Map、Set 等。

const colors = ['red', 'green', 'blue'];

for (const color of colors) {
console.log(color);
}

如果需要获取索引,可以通过以下方法(仅限数组)

const colors = ['red', 'green', 'blue'];

for (const [index, value] of colors.entries()) {
console.log(index, value);
}

异常语句

try-catch-finally 循环语句

function divideNumbers(a, b) {
let result;
try {
if (b === 0) {
throw new Error("Division by zero is not allowed");
}
result = a / b;
} catch (error) {
console.error(error.message);
} finally {
console.log("Finally");
}
return result;
}

console.log(divideNumbers(10, 2)); // 输出: 5
console.log(divideNumbers(10, 0)); // Division by zero is not allowed