我们需要编写一个包含字符串文字数组的JavaScript函数。该函数应生成并返回数组中所有可能的字符串组合。
例如-
如果输入数组是-
const arr = ['a', 'b', 'c', 'd'];
那么输出应该是-
const output = ["a", "ab", "abc", "abcd", "abd", "ac", "acd", "ad", "b", "bc", "bcd", "bd", "c", "cd", "d"];
const getCombinations = (arr = []) => { const combine = (sub, ind) => { let result = [] let i, l, p; for (i = ind, l = arr.length; i < l; i++) { p = sub.slice(0); p.push(arr[i]); result = result.concat(combine(p, i + 1)); result.push(p.join('')); }; return result; } return combine([], 0); }; console.log(getCombinations(["a", "b", "c", "d"]));
输出结果
控制台中的输出将是-
[ 'abcd', 'abc', 'abd', 'ab', 'acd', 'ac', 'ad', 'a', 'bcd', 'bc', 'bd', 'b', 'cd', 'c', 'd' ]