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

Toán tử Rest và Spread trong JavaScript

JavaScript ES6 giới thiệu hai toán tử mạnh mẽ sử dụng cú pháp ... (ba chấm) nhưng có mục đích hoàn toàn khác nhau:

1. Toán tử Rest (Rest Operator)

  • Thu thập nhiều phần tử thành một mảng
  • Sử dụng trong tham số hàm hoặc destructuring
  • Cho phép hàm chấp nhận số lượng đối số không xác định

2. Toán tử Spread (Spread Operator)

  • Mở rộng một iterable (mảng, chuỗi, object) thành các phần tử riêng lẻ
  • Sử dụng trong gọi hàm, tạo mảng/object mới, hoặc destructuring

Ví dụ minh họa

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Rest và Spread Operator</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .sample, .result { font-size: 18px; font-weight: 500; margin: 10px 0; }
    button { margin: 5px; padding: 8px 16px; cursor: pointer; }
  </style>
</head>
<body>
  <h1>JavaScript Rest và Spread Operator</h1>
  <div class="sample" id="sample"></div>
  <div style="color: green;" class="result" id="result1"></div>
  <button class="btn" id="spreadBtn">Spread Operator</button>
  <h3> Nhấn để nối mảng bằng spread operator </h3>
  <button class="btn" id="restBtn">Rest Operator</button>
  <div style="color: green;" class="result" id="result2"></div>
  <h3> Nhấn để cộng các số bằng rest operator </h3>
  <script>
    const sampleEle = document.querySelector("#sample");
    const spreadBtn = document.querySelector("#spreadBtn");
    const restBtn = document.querySelector("#restBtn");
    const result1 = document.querySelector("#result1");
    const result2 = document.querySelector("#result2");

    const arr = [2, 3, 4, 5];
    const arr1 = ["a", "b", "c", "d"];
    sampleEle.innerHTML = "arr = [" + arr.join(", ") + "]
arr1 = [" + arr1.join(", ") + "]"; // Rest operator trong tham số hàm function addArr(num, ...ar) { let sum = num; ar.forEach(item => sum += item); result2.innerHTML = "Tổng các phần tử = " + sum; } // Spread operator để nối mảng spreadBtn.addEventListener("click", () => { const combined = [...arr, ...arr1]; result1.innerHTML = "Mảng nối = [" + combined.join(", ") + "]"; }); restBtn.addEventListener("click", () => { addArr(44, 11, 35, 44, 22, 99); // 44 là num, phần còn lại gom vào ar }); </script> </body> </html>

Kết quả

  • Spread: Nối [2,3,4,5] và ["a","b","c","d"] thành [2,3,4,5,"a","b","c","d"]
  • Rest: Gom các đối số 11, 35, 44, 22, 99 thành mảng ar, cộng với num=44 cho tổng = 255

Tóm tắt sự khác biệt:

Đặc điểmRest OperatorSpread Operator
Vị tríĐịnh nghĩa hàm / destructuringGọi hàm / tạo mảng-object / destructuring
Chức năngGom nhiều thành một mảngMở rộng một mảng thành nhiều phần tử
Ví dụfunction f(...args)f(...arr) hoặc [...arr1, ...arr2]