左右子数组和乘积 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/6 12:28:17
我们需要编写一个 JavaScript 函数,该函数接受一个长度为 N(N 应为偶数)的数字数组,并将该数组分成两个子数组(左和右),每个子数组包含 N/2 个元素,然后对子数组求和,然后将两个子数组相乘。
例如:如果输入数组是 −
const arr = [1, 2, 3, 4]
那么输出应该是 −
(2+1) * (3+4) = 21
示例
以下是代码 −
const arr = [1, 2, 3, 4]
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: 0,
right: 0
});
return creds.left * creds.right;
};
console.log(subArrayProduct(arr));
输出
以下是控制台中的输出 −
21
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

