我们需要编写一个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