为了账号安全,请及时绑定邮箱和手机立即绑定

支持具有多个输入的自定义函数中的数组

支持具有多个输入的自定义函数中的数组

拉丁的传说 2021-09-04 17:24:49
我的 google 应用程序脚本中有一个自定义函数,它需要两个变量。我希望这个函数采用两个数组作为参数,但是放置“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 等。
查看完整描述

1 回答

?
繁星淼淼

TA贡献1775条经验 获得超11个赞

问题:

  • 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


查看完整回答
反对 回复 2021-09-04
  • 1 回答
  • 0 关注
  • 148 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信