在具有多个输入的自定义函数中支持数组 [英] Supporting arrays in custom functions with multiple inputs

查看:99
本文介绍了在具有多个输入的自定义函数中支持数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Google Apps脚本中有一个自定义函数,该函数带有两个变量.我希望此函数采用两个数组作为参数,但是放置如果input.map,return input.map(function)"的标准方法不适用于两个变量.

I have a custom function in my google apps script that takes two variables. I want this function to take two arrays for parameters, but the standard approach of putting "if input.map, return input.map(function)" doesn't work with two variables.

我尝试通过输入递归,但是由于函数中有两个,所以不能同时使用这两个.

I have tried recursing through the inputs, but since there are two in the function, it does not work with both.

这不是我正在使用的功能,但存在相同的问题.

this is not the function i am using, but it has the same problem.

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等.

I expect the formula to take two arrays (i.e. A1:A5, B1:B5) and perform the function on each variable -- i.e. returning A1 * B1, A2 * B2 etc.

推荐答案

问题:

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

    • multiply receives two arguments. When multiply is provided as a function argument to Array.map, the first argument will be the element of the array on which map is called and the second argument will be the element's index.
      • 仅在第一个数组x上使用map,然后使用相应的第二个数组y
      • 中的元素
      • Use map only on the first array x and then use elements from the corresponding second array 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

      这篇关于在具有多个输入的自定义函数中支持数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆