使用递归在 JavaScript 中找出数组的乘积
我们需要编写一个 JavaScript 函数,它接收一个整数数组。我们的函数应该执行以下两件事 −
使用递归方法。
计算数组中所有元素的乘积。
最后,它应该返回乘积。
例如 −
如果输入数组是 −
const arr = [1, 3, 6, .2, 2, 5];
那么输出应该是 −
const output = 36;
例子
这部分的代码为 −
const arr = [1, 3, 6, .2, 2, 5];
const arrayProduct = ([front, ...end]) => {
if (front === undefined) {
return 1;
};
return front * arrayProduct(end);
};
console.log(arrayProduct(arr));输出
控制台中的输出为 −
36
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP