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

Khác biệt giữa Default Parameters và Rest Parameters trong JS

Default Parameters (Tham số mặc định)

Cho phép khởi tạo tham số với giá trị mặc định nếu không truyền giá trị hoặc truyền undefined.

Ví dụ

<html>
  <body>
    <script>
      function inc(val1, inc = 1) { return val1 + inc; }
      document.write(inc(10, 10)); // 20
      document.write("<br>");
      document.write(inc(10));     // 11
    </script>
  </body>
</html>

Rest Parameters (Tham số rest)

ES6. Ký hiệu ... trước tên tham số cuối. Gom tất cả đối số còn lại thành một mảng (Array instance).

Ví dụ

<html>
  <body>
    <script>
      function addition(...numbers) {
        var res = 0;
        numbers.forEach(function(n) { res += n; });
        return res;
      }
      document.write(addition(3));           // 3
      document.write(addition(5, 6, 7, 8, 9)); // 35
    </script>
  </body>
</html>