在 JavaScript 中使用 reduce() 查找数组元素的乘积
问题
我们需要编写一个接受数组arr的JavaScript函数。我们的函数应该找到并返回数组中所有元素的乘积。
示例
以下是代码-
const arr = [3, 1, 4, 1, 2, -2, -1]; const produceElements = (arr = []) => { const res = arr.reduce((acc, val) => { acc = acc * val; return acc; }, 1); return res; }; console.log(produceElements(arr));输出结果
以下是控制台输出-
48