使函数接受可变数量的参数或数组中的值

时间:2017-05-30 12:24:22

标签: javascript arguments

在JavaScript中,现在很容易让函数接受可变数量的参数:

function doSomething(...args) {
    args.forEach(arg => console.log(arg));
}

现在可以像doSomething(1, 2, 3)一样调用它,并且所有参数都可以作为数组args在函数内部使用。输出将是:

1
2
3

现在我想调用该函数,将所有值传递到一个数组中,如下所示:

const arr = [1, 2, 3];
doSomething(arr);

并得到相同的结果。要做到这一点,我必须在函数中使用lodash's _.flatten

doSomething(...args) {
    args = _.flatten(args);
    ...
}

有没有更好的方法来修改我的功能来做到这一点?

我不需要任何解决方案,我已经有了。我需要很好的解决方案,完全符合我的需要,但没有像Lodash这样的第三方库,仍然很优雅。我问是因为好奇,不是因为我根本不知道如何做到这一点: - )

2 个答案:

答案 0 :(得分:1)

看看apply

function doSomething (...args) {
  args.forEach(arg => console.log(arg));
}

const arr = [1, 2, 3];
doSomething.apply(null, arr);

或检查第一个参数是否为数组:

function doSomething () {
  let args;
  if (Array.isArray(arguments[0])) {
    args = arguments[0];
  } else {
    args = Array.slice(argument);
  }
  args.forEach(arg => console.log(arg));
}

const arr = [1, 2, 3];
doSomething.apply(null, arr);

然而,这种方法有点冗长,并没有使用扩展运算符。此外,这样的事情也行不通:

const arr = [[1, 2], [3, 4]];
doSomething.apply(null, arr);

答案 1 :(得分:1)

如果您不想展平所有数组但只使用一个,那么应该执行以下操作:

if (Array.isArray(args[0])) args = args[0];

在这种情况下,您可能还想检查args.length == 1

但总的来说,不是重载你的函数来用不同的数字或类型参数做不同的事情,而是提供多个函数更容易和更安全:

function doSomething(...args) {
    // implementation
}
function doSomethingArr(arr) {
    return doSomething(...arr);
}

function doSomething(...args) {
    return doSomethingArr(args);
}
function doSomethingArr(arr) {
    // implementation
}