我有一个名为“s”的数组,现在我需要从该数组中打印所有内容 “len”的组合/选项现在我有这个代码,但我无法打印全部 选项,我不知道它出了什么问题,最后我需要打印 ABC , BCD , CDE , ABD , , BDE 等......
<html>
<head>
<title>Page Title</title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
</head>
<body>
<p id="result"></p>
<script type="text/javascript">
var s = ["A", "B", "C", "D", "E"];
var len = 2
for (var i = 0; i < s.length - len + 1; i++) {
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML + s.slice(i, i + len) + "<br/>";
}
</script>
</body>
</html>
最佳答案
您可以迭代所有元素的树,其中您使用该元素进入一个方向,而没有实际元素进入另一个方向。继续操作,直到临时数组达到所需的长度或者到达数组的最后一个元素。
仅返回三个元素。
基本上,您需要一个递归函数来检查是否离开该函数。
在这种情况下有两个
如果 temp 数组的长度与所需长度匹配,则将 temp 添加到结果中;
如果索引等于包含该项目的数组的长度;
然后退出函数并停止递归。
主要部分是开始一个新的递归,一个包含索引处的元素,另一个不包含索引处的元素。
function getCombinations(array, length) {
function fork(i, t) { // recursive fn with index & temp array
if (t.length === length) { // check temp length
result.push(t); // push collected values
return; // exit function
}
if (i === array.length) { // check if index is out of range
return; // exit function
}
fork(i + 1, t.concat([array[i]])); // call for with a new letter from index
fork(i + 1, t); // call for without a new letter
}
var result = []; // for keeping the part results
fork(0, []); // start with index zero and empty temp array
return result; // return result
}
var names = ['anne', 'bert', 'cara', 'dirk', 'eva'],
result = getCombinations(names, 3);
document.getElementById('out').innerHTML = JSON.stringify(result, 0, 4);
<pre id="out"></pre>
关于javascript - 与长度集数组的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43014772/