首页 > 解决方案 > 在具有多个输入的自定义函数中支持数组

问题描述

我的谷歌应用程序脚本中有一个自定义函数,它需要两个变量。我希望这个函数采用两个数组作为参数,但是放置“if input.map, return input.map(function)”的标准方法不适用于两个变量。

我已经尝试通过输入递归,但由于函数中有两个,它不能同时使用。

这不是我正在使用的功能,但它有同样的问题。

function multiply(x,y)
{
    if (x.map){
    return x.map(multiply)
    }
    if (y.map){
    return y.map(multiply)
    }
    return x * y
}

我希望公式采用两个数组(即 A1:A5、B1:B5)并对每个变量执行函数——即返回 A1 * B1、A2 * B2 等。

标签: javascriptgoogle-apps-scriptgoogle-sheets

解决方案


问题:

  • multiply接收两个参数。当multiply作为函数参数提供给Array.map时,第一个参数将是调用 map 的数组的元素,第二个参数将是元素的索引。

解决方案:

  • 仅在第一个数组上使用 map x,然后使用对应的第二个数组中的元素y

片段:

function multiply(x, y) {
  if (x.map) {
    return x.map(function(xEl, i) {
      yEl = y.map ? y[i] : y; // corresponding y Element
      return multiply(xEl, yEl);
    });
  }
  if (y.map) {//used, when y is a array and x is number
    return multiply(y, x);
  }
  return x * y;// default 
}

a = [[1],[2]];
b= [[3],[4]];
c= [[5,6],[7,8]];
d= [[1,2],[3,4]];
console.log(JSON.stringify(multiply(a,b)));
console.log(JSON.stringify(multiply(a,5)));
console.log(JSON.stringify(multiply(5,b)));
console.log(JSON.stringify(multiply(c,d)));
console.log(JSON.stringify(multiply(c,2)));
console.log(JSON.stringify(multiply(a,c))); //trims c
console.log(JSON.stringify(multiply(c,a)));//throws error

参考:


推荐阅读