【发布时间】:2021-07-06 09:51:38
【问题描述】:
给自己做了一个有趣的小任务: 构建一个 JS 函数,当从另一个函数中调用该函数时,返回传递给该函数的第一个过多参数。
例如
/**
* Returns first excessive argument of a function, if any
* @param {function} context - function to refer to
*/
function getExcessiveArgument( context ){
// I know I cannot access arguments and length like that,
// but that's what I'd do if I could.
// arguments being the array of all arguments,
// length - the number of expected arguments
return context.arguments[ context.length ];
}
function ReturnExcessive(a,b){
// this is NOT correct as well,
// but I would pass called function's context there, if I could
return getExcessiveArgument( this );
}
ReturnExcessive( 1,2,7); // Should return 7
另一种方法是使用 arguments 和 length 调用 getExcessiveArgument 函数,但我不知道如何访问 length 甚至在父函数中。
有没有可能在 JS 中编写这样的函数,还是我在浪费时间?
提前致谢!
【问题讨论】:
-
OK 对于
function f(a, b) {}调用f(1, 2, 7)有7过度。调用g(1, 2, 7)中的function g(a, b = 0) {}是2还是7第一个多余的参数呢? -
@VLAZ 是的,function.length 停止处理具有默认值的第一个参数,因此根据 JS 2 和 7,在这种情况下不是过多的参数。很遗憾。它实际上扼杀了整个想法,所以我想我一直试图弄清楚的事情根本不可能。
-
没错,
fn.length只计算声明的非默认参数。如果您有function foo() { return arguments[0] + arguments[1]}也不会记录 - 因为该函数没有 declare 参数,length将为零,即使它使用arguments获取前两个参数。此外,length将与其余参数function bar(a, ...b) {}不准确。因此,为什么了解什么被认为是“过度”很重要。如果它与 JS 的fn.length不一致,那么您可以在函数定义上使用 AST 解析器来检查参数。
标签: javascript function arguments