本文介绍使用 javascript 的 `reduce` 方法,结合自定义乘法函数,实现对 n 个同长度数组的逐元素相乘,适用于动态数量(0 到 n)输入场景,并附带边界处理与性能优化建议。
在实际开发中,我们常需对多个结构一致的数组(如时间序列数据、向量批量运算)执行逐元素乘法——例如将 4 个 [1,2,3,4] 相乘得到 [1,16,81,256]。核心挑战在于:输入数组数量不固定(可能为 0、1 或更多),且必须保证所有数组长度一致、安全健壮。
推荐采用函数式链式思路:用 Array.prototype.reduce() 作为主干流程,将累计结果(acc)与当前数组(curr)逐次合并;再封装一个纯函数 multiplyArrays 负责两个数组间的逐项相乘。注意:避免直接修改原数组(原答案中 forEach 改写 arr1 存在副作用),应返回新数组以保障不可变性与可预测性。
以下是生产就绪的实现:
const multiplyArrays = (a, b) => {
if (a.length !== b.length) {
throw new Error(`Array length mismatch: ${a.length} ≠ ${b.lengt
h}`);
}
return a.map((val, i) => val * b[i]);
};
const multiplyAll = (arrays) => {
// 边界处理:空数组 → 返回空数组;单数组 → 返回副本(避免引用污染)
if (arrays.length === 0) return [];
if (arrays.length === 1) return [...arrays[0]];
return arrays.reduce((acc, curr) => multiplyArrays(acc, curr));
};
// 示例调用
const input = [
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]
];
console.log(multiplyAll(input)); // [1, 16, 81, 256]
// 其他用例
console.log(multiplyAll([])); // []
console.log(multiplyAll([[5, 10]])); // [5, 10]
console.log(multiplyAll([[2,3], [4,5], [1,2]])); // [8, 30]✅ 关键优势:
⚠️ 注意事项:
此方案简洁、可读性强,是处理动态多数组逐元素运算的标准实践。