我想返回递归查找字符串排列后生成的数组的长度。代码运行良好,并生成正确的排列数组,但当我尝试返回filtered.length
时,我会收到以下错误消息:Uncaught TypeError: otherPerms is not iterable
。
当我试图在筛选所需结果之前返回数组的长度时,也会出现同样的错误。
如果Ireturn 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"))