我需要在js.Is中限制函数的参数。有什么方法可以在调用时设置函数参数限制。
答案 0 :(得分:0)
不,你不能。但是,参数数量存在限制,并且它依赖于实现(浏览器,后端技术,等等。)。有没有办法允许函数在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!
答案 1 :(得分:0)
您可以使用其他功能作为"中间件功能"
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)
答案 2 :(得分:0)
否。您永远不能真正限制所接受的参数数量。任何函数都可以使用任意数量的参数运行。
但是,您可以创建一个更高阶的函数来包装函数,以便控制包装函数接收的参数数量:
function limitArgs(maxArgs, fn) {
return function(...allArgs) {
const limitedArgs = allArgs.slice(0, maxArgs);
return fn(...limitedArgs);
};
}
当调用此函数limitArgs
时,会发生以下情况:
maxArgs
,用于定义包装函数最多必须接收的参数数量。fn
,这是限制参数的函数。maxArgs
>的数组。给出函数的参数。然后它将调用fn
仅传播创建的参数数组。工作示例:
// 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]'