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

Cách dùng arguments object với Rest, Default và Destructured parameters trong JavaScript

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

ES6 hỗ trợ đặt giá trị mặc định cho tham số. Chỉ áp dụng 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 (dùng mặc định inc=1)
    </script>
  </body>
</html>

2. Rest Parameters (Tham số rest)

ES6 đưa ra rest parameter (ba chấm ...) để thu gom nhiều đối số thành mảng thật.

Ví dụ

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

3. Destructuring (Phân rã)

ES6 cho phép phân rã mảng/đối tượng thành các biến riêng lẻ. Nếu không tìm thấy giá trị, trả về undefined.

Ví dụ

<html>
  <body>
    <script>
      let marks = [92, 95, 85];
      let [val1, val2, val3] = marks;
      document.write("Value 1: " + val1);
      document.write("<br>Value 2: " + val2);
      document.write("<br>Value 3: " + val3);
    </script>
  </body>
</html>

Lưu ý: Rest parameters (...args) là mảng thật, thay thế arguments object (array-like). Nên dùng rest parameters trong code hiện đại.