猿问

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

我的 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 等。


拉丁的传说
浏览 149回答 1
1回答

繁星淼淼

问题: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 cconsole.log(JSON.stringify(multiply(c,a)));//throws error
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答