【问题标题】:How to pass arguments array to another function in JavaScript? [duplicate]如何将参数数组传递给 JavaScript 中的另一个函数? [复制]
【发布时间】:2013-11-21 04:50:45
【问题描述】:

我有一个 JavaScript 函数:

function test() {
  console.log(arguments.length);
}

如果我用test(1,3,5) 调用它,它会打印出3,因为有3 个参数。如何从另一个函数中调用 test 并传递另一个函数的参数?

function other() {
  test(arguments); // always prints 1
  test(); // always prints 0
}

我想调用 other 并让它调用 test 及其 arguments 数组。

【问题讨论】:

    标签: javascript function arguments


    【解决方案1】:

    你为什么不尝试像这样传递参数?

    function other() {
      var testing=new Array('hello','world');
      test(testing); 
    }
    function test(example) {
      console.log(example[0] + " " + example[1]);
    }
    

    输出:hello world

    这是一个有效的JSFiddle

    【讨论】:

    • 我认为 OP 只是想知道如何将动态参数传递给其他函数而无需硬编码
    • 如果要调用的测试函数是由其他包制作或封装的,他只想将相同的参数传递给该函数。
    【解决方案2】:

    看看apply()

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

    function other(){
        test.apply(null, arguments);
    }
    

    【讨论】:

    • 我想你的意思是test.apply(this, arguments);
    • "如果方法是非严格模式代码中的函数,null和undefined将被替换为全局对象,原始值将被装箱。"但是,是的,无论哪种方式都可以。 this只有在你真正想通过的时候才需要使用。
    • 完美运行,谢谢!
    猜你喜欢
    • 2014-03-08
    • 2012-10-17
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 2013-12-25
    相关资源
    最近更新 更多