将数组转换为rest参数

时间:2017-07-19 21:23:29

标签: javascript recursion ecmascript-6

如何使chain使用扩展参数(...chain)而不是数组?

let newData,
    newArgs,
    chain = function (data, myargs) {
        if (myargs.length === 0) {
            return;
        }
        newData = myargs[0](data);

        myargs.splice(0, 1);
        newArgs = myargs;
        // newargs === array
        chain(newData, newArgs);
    },
    add1 = (num) => {
        return num + 1;
    };

当我调用该函数时,我必须这样做:chain(5, [add1, add1, add1])

但我想:chain(5, add1, add1, add1)

问题是,newArgs(递归中的函数参数)在第一次函数调用后被转换为数组。

https://jsfiddle.net/btx5sfwh/

2 个答案:

答案 0 :(得分:2)

您可能希望在递归调用函数时使用rest arguments,然后使用spread数组

UPDATE table1 t JOIN (
  SELECT Opportunity_ID, Opportunity_Record_Type, Opportunity_Division, Fiscal_Period
    FROM table1
   WHERE Opportunity_Record_Type IS NOT NULL
     AND Opportunity_Division IS NOT NULL
     AND Fiscal_Period IS NOT NULL
   GROUP BY Opportunity_ID, Opportunity_Record_Type, Opportunity_Division, Fiscal_Period
  ) q
    ON t.Opportunity_ID = q.Opportunity_ID
   SET t.Opportunity_Record_Type = q.Opportunity_Record_Type,
       t.Opportunity_Division = q.Opportunity_Division,
       t.Fiscal_Period = q.Fiscal_Period
 WHERE t.Opportunity_Record_Type IS NULL
    OR t.Opportunity_Division IS NULL
    OR t.Fiscal_Period IS NULL

答案 1 :(得分:2)

您可以以更好的方式撰写chain

const chain = (x, f, ...fs) =>
  f === undefined
    ? x
    : chain (f (x), ...fs)
    
const add1 = x =>
  x + 1
    
console.log (chain (5, add1, add1, add1)) // 8
console.log (chain (5))                   // 5

Rest参数和spread参数有些昂贵 - 我们通常希望限制我们对这些的依赖,但我们不想牺牲我们想要的API。

别担心,有一个更高层次的方式来思考这个问题。我们可以保留可变参数API但避免代价高昂的传播参数。

const chain = (x, ...fs) =>
  fs.reduce((x, f) => f (x), x)

const add1 = x =>
  x + 1

console.log (chain (5, add1, add1, add1)) // 8
console.log (chain (5))                   // 5