将数组转换为单独的参数字符串

时间:2009-11-25 00:05:25

标签: javascript

如何将此数组作为一组字符串传递给函数?这段代码不起作用,但我认为它说明了我正在尝试做的事情。

var strings = ['one','two','three'];

someFunction(strings.join("','")); // someFunction('one','two','three');

谢谢!

3 个答案:

答案 0 :(得分:42)

使用apply()

var strings = ['one','two','three'];

someFunction.apply(null, strings); // someFunction('one','two','three');

如果您的函数关注对象范围,请将您想要设置的this作为第一个参数而不是null传递。

答案 1 :(得分:12)

对于ES6 JavaScript,您可以使用特殊的'解构'操作者:

var strings = ["one", "two", "three"];
someFunction(...strings);

参考:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operatorhttp://www.2ality.com/2015/01/es6-destructuring.html

对于ES5 JavaScript,您可以:

var strings = ["one", "two", "three"];
someFunction.apply(this, strings);

答案 2 :(得分:11)

解决方案相当简单,JavaScript中的每个函数都有一个与之关联的方法,称为“apply”,它将您想要传入的参数作为数组传递。

所以:

var strings = ["one", "two", "three"];
someFunction.apply(this, strings);

apply中的'this'表示范围,如果它只是页面中没有对象的函数,则将其设置为null,否则,传递调用它时希望方法具有的范围。

反过来,在someFunction内部,您可以编写如下代码:

function someFunction() {
  var args = arguments; // the stuff that was passed in
  for(var i = 0; i < args; ++i) {
    var argument = args[i];
  }
}
相关问题