JavaScript 中的子数组乘积和
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/16 20:28:17
我们需要编写一个 JavaScript 函数,该函数接受一个长度为 N 的数字数组,其中 N 是正偶数,并将该数组分成两个子数组(例如,左和右),每个子数组包含 N/2 个元素。
该函数应该对子数组进行乘积,然后将得到的结果相加。
例如,如果输入数组是 −
const arr = [1, 2, 3, 4, 5, 6]
那么输出应该是 −
(1*2*3) + (4*5*6) 6+120 126
其代码为 −
const arr = [1, 2, 3, 4, 5, 6]
const subArrayProduct = arr => {
const { length: l } = arr;
const creds = arr.reduce((acc, val, ind) => {
let { left, right } = acc;
if(ind < l/2){
left *= val;
}else{
right *= val;
}
return { left, right };
}, {
left: 1,
right: 1
});
return creds.left + creds.right;
};
console.log(subArrayProduct(arr));
以下是控制台上的输出 −
126
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

