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

Sử dụng số lượng đối số biến đổi (Variable Arguments) cho Function trong JavaScript


Để dùng số lượng argument biến đổi, dùng object arguments (built-in trong function non-arrow).

Ví dụ

<html>
  <body>
    <script>
      function functionArgument(val1, val2, val3) {
        var res = "";
        res += "Expected Arguments: " + functionArgument.length; // 3 (số parameter định nghĩa)
        res += "<br />";
        res += "Current Arguments : " + arguments.length; // Số argument thực tế truyền vào
        res += "<br />";
        res += "Each argument = ";
        for (var p = 0; p < arguments.length; p++) {
          res += "<br />";
          res += arguments[p];
          res += " ";
        }
        document.write(res);
      }
      functionArgument(20, 50, 80, "Demo Text!", "Hello World", new Date());
    </script>
  </body>
</html>

arguments Object - Đặc điểm

  • Array-like object: có length, index 0, 1, 2....
  • Không phải Array - không có .map(), .forEach(), .filter()...
  • Có sẵn trong mọi function non-arrow.
  • ES5: Array.prototype.slice.call(arguments) để convert sang array.

ES6+: Rest Parameters (Khuyên dùng)

// Rest parameter - Array thật, dùng được methods
function modern(...args) {
  console.log("Count:", args.length);
  console.log("Args:", args);
  args.forEach((arg, i) => console.log(i, arg));
  
  // Dễ dàng filter, map, reduce
  const numbers = args.filter(x => typeof x === 'number');
  return numbers.reduce((a, b) => a + b, 0);
}

modern(1, 2, "hello", 3, "world", 4); // Sum numbers = 10

arguments trong Arrow Function

Arrow function không có arguments object. arguments trong arrow function tham chiếu đến arguments của outer function (nếu có) hoặc ReferenceError.

Spread với arguments

function legacy(...args) {
  // Convert arguments to array (ES5 style)
  const argsArray = Array.from(arguments);
  // hoặc
  const argsArray2 = [...arguments];
  return argsArray;
}

Best Practice

  • Ưu tiên Rest Parameters (...args): Array thật, methods đầy đủ, rõ ràng, tương thích arrow function.
  • Dùng arguments chỉ khi: maintain legacy code, cần truy cập tất cả args bao gồm named params, hoặc trong function non-arrow không thể đổi signature.
  • function.length = số parameter định nghĩa (không tính rest). arguments.length = số argument thực tế truyền vào.