我已经在这个问题上停留了一段时间。除了不使用内置方法和length属性之外,我们也不能使用任何循环,这是必须通过递归解决此问题的一种选择。我已经尝试过此功能,但仍然无法使用。
function getLength(string, length = 0){
if (string[0] === undefined) {return length};
length++;
return getLength(length);
}
console.log(getLength("hello"))
// expected answer: 5
您非常亲密。
function getLength(string, length = 0){
if (string[length] === undefined) {return length};
length++;
return getLength(string, length);
}
console.log(getLength("hello"))
// expected answer: 5
您已经找到答案,只是错过了几个参数
function getLength(string, length = 0) {
if (string[length] === undefined) {
return length
};
length++;
return getLength(string, length);
}
console.log(getLength("hello"))
您可以定义递归的base case,它将终止递归,就像传递的字符串是empty /undefined
/ null
或您所处的索引时一样在递归过程中已超过给定字符串的长度,在这种情况下,您将返回0
。
然后通过递增字符串的索引并在每个递归过程中添加1
直到达到基本条件,来递归调用函数:
function getLength(str, idx = 0) {
//base case
if (!str || !str[idx]) {
return 0;
}
return 1 + getLength(str, idx + 1);
}
console.log(getLength("hello"));