javascript - 有没有办法判断一个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
解决方案
在正则表达式方面我不是那么好,但我认为这样的事情在大多数情况下都会起作用:
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");
推荐阅读
- angular - 升级到 Angular 9
- r - 如何减少分组的堆积条形图之间的空白
- primefaces - p:ajax 中的 actionListener
- ruby-on-rails - 使用表单在 Rails 中保存 jsonb 字段的最佳方法
- r - R中年龄金字塔图的问题,蓝线
- django-sites - Django 站点地图.xml。为什么我在文件中得到 example.com?
- stm32 - STM32H7 SPI通信:FIFO管理问题
- python - 在 Jupyter notebook 中用 pandas 读取 csv
- javascript - Tampermonkey GM.xmlHttpRequest 不是函数
- c# - 从List中填充ICollection,ICollection返回null