Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tiếp tục vòng lặp (Continue) trong lập trình hàm JavaScript

Continue trong Functional Programming

Trong lập trình hàm, không dùng từ khóa continue (chỉ dùng trong vòng lặp for/while). Thay vào đó, dùng các phương thức mảng:

  • filter() - Lọc bỏ phần tử không muốn (tương đương continue).
  • forEach() - Không thể break/continue, nhưng có thể return sớm (chỉ bỏ qua iteration hiện tại).
  • some()/every() - Có thể dừng sớm (return true/false).

Ví dụ minh họa: Bỏ qua "xoài" và "đào" với some()

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Continue in FP</title>
    <style>
        body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
        .result { font-size: 18px; font-weight: 500; color: rebeccapurple; font-family: monospace; }
        button { padding: 8px 16px; cursor: pointer; }
    </style>
</head>
<body>
    <h1>Continue trong Functional Programming</h1>
    <div class="result"></div>
    <button class="btn-demo">LẶP VỚI SOME()</button>
    <h3>Nhấn nút để duyệt mảng, bỏ qua xoài và đào</h3>

    <script>
        const resEle = document.querySelector(".result");
        const btn = document.querySelector(".btn-demo");

        const fruits = ["táo", "xoài", "đào", "đu đủ", "dưa hấu"];

        btn.addEventListener("click", () => {
            resEle.textContent = "";
            
            // some() dừng khi callback return true
            // Dùng return false để "continue" (tiếp tục)
            // Dùng return true để "break" (dừng)
            fruits.some(function(fruit) {
                if (fruit === "xoài" || fruit === "đào") {
                    return false; // Continue - bỏ qua, tiếp tục phần tử sau
                }
                resEle.textContent += fruit + "\n";
                return false; // Continue
            });
            
            resEle.textContent += "\n--- So sánh ---\n";
            resEle.textContent += "filter() cách hay hơn:\n";
            fruits.filter(f => f !== "xoài" && f !== "đào")
                  .forEach(f => resEle.textContent += f + "\n");
        });
    </script>
</body>
</html>

Phân tích some() làm continue/break

const arr = [1, 2, 3, 4, 5];

// CONTINUE: Bỏ qua 3, in 1,2,4,5
arr.some(x => {
    if (x === 3) return false; // continue
    console.log(x);
    return false; // continue
});

// BREAK: Dừng khi gặp 3, in 1,2
arr.some(x => {
    if (x === 3) return true; // break
    console.log(x);
    return false; // continue
});

Cách tốt hơn: filter() + forEach()

// Declarative style - khuyến nghị
const fruits = ["táo", "xoài", "đào", "đu đủ", "dưa hấu"];

// Bỏ qua xoài, đào
const filtered = fruits.filter(f => f !== "xoài" && f !== "đào");
// ["táo", "đu đủ", "dưa hấu"]

filtered.forEach(f => console.log(f));
// Hoặc gọn hơn:
fruits.filter(f => !["xoài", "đào"].includes(f))
      .forEach(f => console.log(f));

So sánh các phương thức

Phương thức Continue Break Trả về
forEachreturn (bỏ qua phần tử hiện tại)Không thể (ném exception)undefined
somereturn falsereturn trueBoolean
everyreturn truereturn falseBoolean
filterLọc trước, rồi forEachKhông áp dụngMảng mới
findN/ATìm thấy đầu tiênPhần tử

Khi nào dùng gì?

  • filter + forEach: Đọc dễ, rõ ý đồ, hiệu suất tốt (khuyến nghị).
  • some/every: Cần dừng sớm (short-circuit) dựa trên điều kiện.
  • for...of loop: Cần break/continue thực sự, logic phức tạp.