JavaScript:在采取可变数量的参数转发函数调用 [英] Javascript: Forwarding function calls that take variable number of arguments

查看:80
本文介绍了JavaScript:在采取可变数量的参数转发函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我需要像Ruby的图示 * 在这里。

I think I need something like ruby's splat * here.

function foo() {
  var result = '';
  for (var i = 0; i < arguments.length; i++) {
    result += arguments[i];
  }
  return result;
}

function bar() {
  return foo(arguments) // this line doesn't work as I expect
}

bar(1, 2, 3);

我想这回123,而是我得到[对象参数]。这是有道理的,我想。它通过单独的重新presents参数的对象,而不是争论。

I want this to return "123", but instead I get "[object Arguments]". Which makes sense, I suppose. It's passing the object that represents the arguments, but not the arguments individually.

那么,如何做,我只是提出任何数量的参数给另一个函数,它接受任何数量的参数?

So how do I simply forward any number of arguments to another function that takes any number of arguments?

推荐答案

要正确地传递参数给另一个函数,你需要使用<一个href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Function/apply\"><$c$c>apply:

To correctly pass the arguments to another function, you need to use apply:

function bar() {
  return foo.apply(null, arguments);
}

适用方法有两个参数,第一个是 thisObj ,它的价值将被用作在被调用的函数内部的价值,如果你使用未定义在函数内部此值指的是全局对象。

The apply method takes two parameters, the first is the thisObj, the value of it will be used as the this value inside the invoked function, if you use null or undefined, the this value inside the function will refer to the global object.

第二个参数是适用预计,中,包含参数数组状物体被应用到的功能。

The second argument that apply expects, is an array-like object that contains the arguments to be applied to the function.

这里检查上面的例子

Check the above example here.

这篇关于JavaScript:在采取可变数量的参数转发函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆