首页 > 解决方案 > 有没有办法判断一个javascript函数是否使用了一个rest参数?

问题描述

我正在使用一个库来解析命令并将函数应用于它们的参数,并在应用函数之前检查参数的数量是否正确。它通过检查length函数的参数来做到这一点。但是,如果我传入一个可变参数函数,那么当我传递任何参数时,此检查将失败,因为length不包括其余参数。

有没有一种方法可以检查函数是否使用 rest 参数来显式处理可变数量的参数?

复制:

function call_function(f, ...args) {
  if (f.length === args.length) {
    f(...args);
  } else {
    console.log("error! wrong number of arguments!");
  }
}

function normal_function(arg1) {
  console.log("here's the argument: ", arg1);
}

function variadic_function(...args) {
  console.log("here are the arguments: ", ...args);
}

call_function(normal_function, "hello"); // here's the argument: hello
call_function(variadic_function, "hello"); // error! wrong number of arguments!
call_function(variadic_function, "hello", "there"); // error! wrong number of arguments!

normal_function("hello"); // here's the argument: hello
variadic_function("hello"); // here are the arguments: hello
variadic_function("hello", "there"); // here are the arguments: hello there

标签: javascriptfunctionvariadic-functions

解决方案


在正则表达式方面我不是那么好,但我认为这样的事情在大多数情况下都会起作用:

const isVariadicFunction = f => /\.{3}[a-zA-Z0-9$_]+\s*\)/.test(f.toString());

function call_function(f, ...args) {
  if (f.length === args.length || isVariadicFunction(f)) {
    f(...args);
  } else {
    console.log("error! wrong number of arguments!");
  }
}

function normal_function(arg1) {
  console.log("here's the argument: ", arg1);
}

function variadic_function(...args) {
  console.log("here are the arguments: ", ...args);
}

call_function(normal_function, "hello");
call_function(variadic_function, "hello");
call_function(variadic_function, "hello", "there");


推荐阅读