我想返回递归查找字符串排列后生成的数组的长度。该代码工作正常,并产生排列的正确阵列,但是当我尝试返回filtered.length
我收到以下错误信息:Uncaught TypeError: otherPerms is not iterable
。
当我在过滤数组以获得我想要的结果之前尝试返回数组的长度时,也会发生同样的错误。
如果我return filtered
然后调用该函数,以下效果很好:
let permutation = permutate('aab'); console.log(permutation.length); // 2 console.log(permutation); // ["aba", "aba"]
但我希望能够从函数内部返回数组的长度。
下面的代码按预期工作,直到我尝试返回生成的数组的长度:
function permutate(str) {
let result = [];
if (str.length === 1) {
result.push(str);
}
for (let i = 0; i < str.length; i++) {
var firstChar = str[i];
var otherChar = str.substring(0, i) + str.substring(i + 1);
var otherPerms = permutate(otherChar);
for (let perm of otherPerms) {
result.push(firstChar + perm);
}
}
let filtered = result.filter((str) => !(/(\w)\1/).test(str)); // To get permutations with non-repeating adjacent letters
return filtered;
}
如果您尝试从函数内部返回长度,则递归将不起作用,因为您不再返回“otherPerms”所需的内容。
如果您希望它返回长度,则必须将该函数包装在另一个函数中
function permutate(str) {
return recursivePermutate(str).length;
function recursivePermutate(str) {
let result = [];
if (str.length === 1) {
result.push(str);
}
for (let i = 0; i < str.length; i++) {
var firstChar = str[i];
var otherChar = str.substring(0, i) + str.substring(i + 1);
var otherPerms = recursivePermutate(otherChar);
for (let perm of otherPerms) {
result.push(firstChar + perm);
}
}
let filtered = result.filter((str) => !(/(\w)(?=\1)/).test(str)); // To get permutations with non-repeating adjacent letters
return filtered;
}
}
console.log(permutate("ab"))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句