var subsequences = function(s) {
if (s==="") {
return s
} else {
var firstLetter = s.charAt(0)
var restOfWord = s.substring(1)
我正在尝试实现功能
答案 0 :(得分:0)
您正在使用for..in
循环,该循环用于迭代对象,而不是数组。而是在.split()
方法调用返回的数组上使用Array.forEach()
方法。
您还应该养成用分号和not rely on automatic semi-colon insertion结束语句的习惯。
var subsequences = function(s) {
if (s==="") {
return s;
} else {
var firstLetter = s.charAt(0);
var restOfWord = s.substring(1);
var subsequencesOfRest = subsequences(restOfWord);
var result = "";
subsequencesOfRest.split(",").forEach(function(item){
result += "," + item;
result += "," + firstLetter + item;
});
result = result.substring(1);
return result;
}
};
console.log(subsequences("gc"))
答案 1 :(得分:0)
您应该使用in
来迭代数组,而不是使用of
。
您需要更改的只是一个字:
var subsequences = function(s) {
if (s==="") {
return s
} else {
var firstLetter = s.charAt(0)
var restOfWord = s.substring(1)
var subsequencesOfRest = subsequences(restOfWord)
var result = ""
for (var subsequence of subsequencesOfRest.split(",")) {
result += "," + subsequence
result += "," + firstLetter + subsequence
}
result = result.substring(1)
return result
}
}
console.log(subsequences("gc"))
答案 2 :(得分:0)
使用for of
而不是for in
var subsequences = function(s) {
if (s==="") {
return s
} else {
var firstLetter = s.charAt(0)
var restOfWord = s.substring(1)
var subsequencesOfRest = subsequences(restOfWord)
var result = ""
for (let subsequence of subsequencesOfRest.split(",")) {
result += "," + subsequence
result += "," + firstLetter + subsequence
}
result = result.substring(1)
return result
}
}
console.log(subsequences("gc"))
答案 3 :(得分:0)
重点是for (var subsequence in subsequencesOfRest.split(",")) {
}
当subsequencesOfRest为”时,运行subsequencesOfRest.split(“,”),结果为[“”],
并且子序列是数组中的索引,因此子序列为0。