javascript - 在具有多个输入的自定义函数中支持数组
问题描述
我的谷歌应用程序脚本中有一个自定义函数,它需要两个变量。我希望这个函数采用两个数组作为参数,但是放置“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 等。
解决方案
问题:
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
参考:
推荐阅读
- mysql - 存储大量数据的最佳方式 - SQL
- sql - 将字符串拆分为给定长度但不拆分单词
- php - 使用 php 写入文件正在更改原始 EOL 类型
- java - Spring @Service 依赖于 Mongo
- python - AttributeError:“协程”对象没有属性“文本”
- arrays - 如何一次为一个 React 组件做方法映射?
- php - 如何将视频从颤振上传到用 PHP 编写的服务器?
- c - 使用 C Caller 函数将 C 代码放入 simulink
- c# - 寻找一种解决方案,当键盘也是焦点时,可以让我的自定义导航栏保持焦点
- excel - Laravel 将 Excel 数据存入数据库