[英]Is there a way to allow a function to accept definite number of arguments in js
我需要在我的js中限制函数的参数,有什么方法可以在调用时设置函数参数的限制。
有没有一种方法可以让函数在JS中接受一定数量的参数
不,你不能。 但是,自变量的数量受到限制,并且依赖于实现(浏览器,后端技术,等等)。
一种替代方法是检查函数(非箭头函数)中隐式arguments
数组的长度。
例如:
我假设你想抛出一个错误
function fn(a, b, c) { if(arguments.length > 3) throw new Error('Too many arguments!'); console.log(arguments[0], arguments[1], arguments[2]); } fn('Ele', 'from', 'SO'); // Will work! fn('Ele', 'from', 'SO', 'Hello!'); // Won't work!
您可以将另一个功能用作“中间件功能”
function invoker(func, ...args) {
if (args.length > 4) throw new Error('Too many arguments!');
else if (typeof(func) === "function") func.apply(null,args)
}
function foo (...args) {
console.log(args.length)
}
运行invoker(foo, 1,2,3,4,5)
将引发错误。 运行invoker(foo, 1,2,3,4)
将运行foo(1,2,3,4)
不。您永远不能真正限制可接受的参数数量。 任何函数都可以使用任意数量的参数运行。
但是,您可以创建一个包装函数的高阶函数,以控制该包装函数接收的参数数量:
function limitArgs(maxArgs, fn) {
return function(...allArgs) {
const limitedArgs = allArgs.slice(0, maxArgs);
return fn(...limitedArgs);
};
}
当调用该函数limitArgs
时,会发生以下情况:
maxArgs
,该数字定义包装函数最多必须接收多少个参数。 fn
,该函数限制参数。 maxArgs
>参数的数组。 然后它将调用fn
仅传播创建的arguments数组。 工作示例:
// As arrow function oneliner this time: const limitArgs = (maxArgs, fn) => (...allArgs) => fn(...allArgs.slice(0, maxArgs)); const testFn = (...args) => console.log(`Arguments given: [${args}]`); const testFn4 = limitArgs(4, testFn); testFn4(1, 2, 3, 4, 5); // Expected output: 'Arguments given: [1,2,3,4]' const testFn2 = limitArgs(2, testFn); testFn2(1, 2, 3, 4, 5); // Expected output: 'Arguments given: [1,2]'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.