JavaScript 中数组的全部和组合
我们需要编写一个 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 ]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP