【问题标题】:Alternative syntax to access javascript function arguments访问 javascript 函数参数的替代语法
【发布时间】:2021-05-14 13:06:08
【问题描述】:
(function(arguments = {})
{
    console.log(arguments)
}
)("a","b","c")

打印

$ node args.js 
a
$ node --version
v8.9.4

在这种情况下有没有办法访问实际参数?

【问题讨论】:

    标签: javascript arguments


    【解决方案1】:

    我建议不要在 function 定义中覆盖内置的 arguments 变量。

    您可以使用 ...vargs 来传播预期的参数。

    (function(...vargs) {
      console.log(arguments); // Built-in arguments
      console.log(vargs);     // Variable (spread) arguments
    })("a", "b", "c");
    .as-console-wrapper { top: 0; max-height: 100% !important; }

    请查看 MDN 上的 the arguments object 了解更多信息。

    文档指出,如果您使用 ES6 语法,则必须分散参数,因为箭头(lambda 或匿名)函数内部不存在 arguments

    ((...vargs) => {
      try {
        console.log(arguments); // Not accessible
      } catch(e) {
        console.log(e);         // Expected to fail...
      }
      console.log(vargs);       // Variable (spread) arguments
    })("a", "b", "c");
    .as-console-wrapper { top: 0; max-height: 100% !important; }

    【讨论】:

      【解决方案2】:

      function f1() { console.log(Array.from(arguments)) }
      f1(1, 2, 3)
      
      function f2(...args) { console.log(args) }
      f2(4, 5, 6)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-02
        • 2010-11-03
        • 1970-01-01
        • 2012-12-14
        • 1970-01-01
        • 2018-10-06
        • 1970-01-01
        • 2012-10-18
        相关资源
        最近更新 更多