简体   繁体   English

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

[英]Make function accept both variable number of arguments, or values in array

In JavaScript, it is pretty easy now to make a function accept a variable number of arguments: 在JavaScript中,现在让函数接受可变数量的参数非常容易:

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

Now it can be called like doSomething(1, 2, 3) and all arguments will be available inside the function as array args . 现在可以像doSomething(1, 2, 3)那样调用它doSomething(1, 2, 3)并且所有参数都可以在函数内部以数组args The output will be: 输出将是:

1
2
3

Now I want to call the function, passing all values in one array, like this: 现在,我想调用该函数,将所有值传递到一个数组中,如下所示:

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

and have the same result. 并具有相同的结果。 To do it, I have to use lodash's _.flatten inside the function: 为此,我必须在函数内部使用lodash的_.flatten

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

Are there better ways to modify my function to do this? 有更好的方法来修改我的功能来做到这一点吗?

I don't need any solution, I already have one. 我不需要任何解决方案,我已经有了。 I need good solutions doing exactly what I need, but without third party libraries like Lodash and still elegant. 我需要很好的解决方案来完全满足我的需要,但是没有像Lodash这样的第三方库,而且仍然很优雅。 I ask because of curiosity, not because I don't know how to do that at all :-) 我问是出于好奇,而不是因为我根本不知道该怎么做:-)

Take a look at apply : 看一下apply

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

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

Or check if the first argument is an array: 或检查第一个参数是否为数组:

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);

This approach however is a bit more verbose and doesn't make use of the spread operator. 但是,这种方法比较冗长,没有使用散布运算符。 Also, things like this would not work: 同样,这样的事情将不起作用:

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

If you don't want to flatten all arrays but only use one, then the following should do: 如果您不想展平所有数组,而只使用一个,则应执行以下操作:

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

You might also want to check for args.length == 1 in that case. 在这种情况下,您可能还需要检查args.length == 1

But in general, instead of overloading your function to do different things with different numbers or types arguments, it's much easier and safer to provide multiple functions: 但是,总的来说,提供多个函数更容易,更安全,而不是重载函数以使用不同的数字或类型参数来完成不同的事情:

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM