交替的休息参数

问题描述 投票:0回答:2

有没有一种语法上简洁的方法来创建交替的无限量的参数?下面是我想实现的一个例子。

myFunction('foo',1);
///performs action A with 'foo', then action B with 1;

myFunction('foo', 1, 'bar', 2, 'FOO', 3, 'BAR', 4);
///performs action A with 'foo', then action B with 1;
///performs action A with 'bar', then action B with 2;
///performs action A with 'FOO', then action B with 3;
///performs action A with 'BAR', then action B with 4;

我知道你可能会使用休息参数... 但是有什么方法(或者用其他运算符)来实现上面的那种功能吗?

javascript syntax parameters arguments
2个回答
2
投票

你可以使用modulo操作符对偶数索引元素做一件事,对奇数索引元素做另一件事,就像这样。

const doA = (arg) => console.log(`A: ${arg}`);
const doB = (arg) => console.log(`B: ${arg}`);

function myFunction(...args) {
  args.forEach((el, i) => {
    i % 2 === 0 ? doA(el) : doB(el);
  });
}

myFunction("foo", 1, "bar", 2, "baz", 3);

0
投票

是的,你可以很容易地做到这一点 -- 假设我的理解是正确的,你说的 "用'foo'执行动作A "是指 "用foo作为参数调用函数A"。

function myFunction(...args) {
    args.forEach((arg, i) => {
        if (i % 2 === 0) {
            A(arg);
        }
        else {
            B(arg);
        } 
    } 
} 

0
投票

这是对其他答案的一个补充。

如果您不能使用ES6的扩展运算符 ... (首选),你可以使用 arguments 数组来替代 ...args:

https:/developer.mozilla.orgen-USdocsWebJavaScriptReferenceFunctionsarguments。

© www.soinside.com 2019 - 2024. All rights reserved.