【问题标题】:A JS function to fetch first excessive argument of another function一个 JS 函数来获取另一个函数的第一个多余参数
【发布时间】: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  

另一种方法是使用 argumentslength 调用 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


【解决方案1】:

您可以获得arguments 的副本,并使用函数的length 定义参数进行切片。

function fn(a, b) {
    return [...arguments].slice(fn.length);
}

console.log(fn(1, 2, 7)); // 7

【讨论】:

  • 不错,谢谢!现在,是否有一个函数可以从 fn() 中获取它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-02
  • 2023-03-22
  • 2020-06-14
  • 1970-01-01
  • 2012-10-26
相关资源
最近更新 更多