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

Truyền số lượng arguments không xác định vào function trong JavaScript

Gọi function JS có thể truyền bất kỳ số lượng arguments. Không giới hạn tham số. Do đó function không thể overload theo cách truyền thống.

arguments object: Biến local có sẵn trong tất cả non-arrow function. Chứa giá trị arguments truyền vào, index từ 0.

arguments[0] // first argument
arguments[1] // second argument
arguments[2] // third argument

Lưu ý: arguments là Array-like (có length, index từ 0) nhưng không có method mảng (forEach, map...).

Ví dụ: Nhận arguments tùy ý

function printAllArguments(a, b) {
  console.log("First arg: " + a);
  console.log("Second arg: " + b);
  console.log("All args: " + JSON.stringify(arguments));
}
printAllArguments(1);
printAllArguments(1, "hello");
printAllArguments(1, "hello", 1, "hello");

Kết quả

First arg: 1 Second arg: undefined All args: {"0":1}
First arg: 1 Second arg: hello All args: {"0":1,"1":"hello"}
First arg: 1 Second arg: hello All args: {"0":1,"1":"hello","2":1,"3":"hello"}

ES6 Rest Parameters (khuyên dùng):

function printAllArguments(...args) {
  console.log("All args:", args); // args là array thật
  args.forEach((arg, i) => console.log(`Arg ${i}:`, arg));
}

Rest params là array thật, dùng được mọi method mảng. Arrow function không có arguments, bắt buộc dùng rest params.