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

Lambda với Arrow Function trong JavaScript


Lambda là hàm ẩn danh, một biểu thức, có thể truyền như giá trị. Trong JS, arrow function là cách viết lambda phổ biến. Cho phép Higher-Order Functions (hàm nhận hàm làm tham số/trả về hàm).

Ví dụ

Hàm arraySq(func, arr) nhận lambda square và áp dụng cho mỗi phần tử:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Lambda Arrow Function</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .sample, .result { font-size: 20px; font-weight: 500; color: blueviolet; }
    .sample { color: red; }
  </style>
</head>
<body>
  <h1>Lambda với Arrow Function trong JavaScript</h1>
  <div class="sample">[1, 2, 3, 4, 5, 6, 7]</div>
  <div class="result"></div>
  <br />
  <button class="Btn">BÌNH PHƯƠNG MẢNG</button>
  <h3>Nhấn nút để bình phương từng phần tử mảng bằng lambda</h3>
  <script>
    const btn = document.querySelector('.Btn');
    const sampleEle = document.querySelector('.sample');
    const resEle = document.querySelector('.result');
    const arr = [1, 2, 3, 4, 5, 6, 7];
    // Lambda: arrow function một biểu thức
    const square = (item) => item * item;
    function arraySq(func, arr) {
      const newArr = arr.map(func); // Dùng map thay forEach + push
      resEle.textContent = `Mảng mới: [${newArr.join(', ')}]`;
    }
    btn.addEventListener('click', () => arraySq(square, arr));
  </script>
</body>
</html>

Kết quả

Mảng mới: [1, 4, 9, 16, 25, 36, 49].

Lưu ý: Dùng arr.map(func) thay forEach + push ngắn gọn, functional style.