【问题标题】:How to re-assign the arguments of a function back to the original argument names?如何将函数的参数重新分配回原始参数名称?
【发布时间】:2023-03-23 00:06:02
【问题描述】:

我有一个函数可以重新排列另一个函数的参数以满足标准定义。

function main(a, b, c) {
    console.log(a, b, c);                                  // 1 undefined undefined
    console.log(arguments[0], arguments[1], arguments[2]); // 1 undefined undefined

    shiftArgs(arguments, 3); // 3 because I'm expecting 3 arguments.

    console.log(arguments[0], arguments[1], arguments[2]); // null null 1
    console.log(a, b, c);                                  // 1 undefined undefined ***
}



function shiftArgs(args, c) {var i, len; 
   len = args.length; 
   if (len < c) { 
      for (i = c - 1; i >= 0; i -= 1) {
          args[i] = ((i - c + len) >  -1 ? args[i - c + len] : null);
      }
      args.length = c;
   }
};

main(1); // only calling main with one argument, which therefore needs to be the last one.

*** 是问题行,应该是“null null 1”以匹配重新分配的参数对象。

arguments 对象按我的意愿更改,main 调用的值“1”移动到最后一个参数。但是,映射到参数的变量名称在我移动参数对象后不会更改(请参阅最后一个标有 *** 的 console.log)。这需要为 null null 1 以匹配更改的参数对象)。

如何让 shiftArgs 函数重新分配变量 a、b 和 c 以匹配参数对象?

【问题讨论】:

  • 你使用的是严格模式吗?

标签: javascript arguments symbol-table


【解决方案1】:

您不想像那样弄乱参数对象。映射到它的参数变量被认为是错误的,它也不会在严格模式下工作。

最好使用函数装饰器来处理这些事情:

function shiftArgs(fn, c) {
    return function() {
        var lastIdx = arguments.length; 
        if (arguments.length < c)
            for (var i = c-1; i >= 0; i--)
                arguments[i] = ((i - c + lastIdx) >  -1 ? arguments[i - c + lastIdx] : null);
        arguments.length = c;
        return fn.apply(this, arguments);
    };
}

var main = shiftArgs(function(a, b, c) {
    console.log(a, b, c); // null null 1
}, 3);

【讨论】:

    【解决方案2】:

    您是否正在寻找比以下更通用的东西:

    a = arguments[0];
    b = arguments[1];
    c = arguments[2];
    

    ?我比较确定这是不可能的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-10
      • 2019-06-12
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 2011-12-31
      • 1970-01-01
      相关资源
      最近更新 更多