JavaScript 中数组总和的所有组合
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/19 5:32:17
我们需要编写一个 JavaScript 函数,该函数将数字数组作为第一个参数,将数字(例如 n)作为第二个参数。数字 n 始终小于或等于数组的长度。
我们的函数应返回原始数组中所有可能的长度为 n 的子数组的所有元素之和的数组。
例如,如果输入是 −
const arr = [2, 6, 4]; const n = 2;
那么输出应该是 −
const output = [8, 10, 6];
示例
其代码为 −
const arr = [2, 6, 4];
const n = 2;
const buildCombinations = (arr, num) => {
const res = [];
let temp, i, j, max = 1 << arr.length;
for(i = 0; i < max; i++){
temp = [];
for(j = 0; j < arr.length; j++){
if (i & 1 << j){
temp.push(arr[j]);
};
};
if(temp.length === num){
res.push(temp.reduce(function (a, b) { return a + b; }));
};
};
return res;
}
console.log(buildCombinations(arr, n));
输出
控制台中的输出 −
[ 8, 6, 10 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

