在不使用循环,内置方法或javascript中的.length属性的情况下查找字符串的长度?

问题描述 投票:1回答:3

我已经在这个问题上停留了一段时间。除了不使用内置方法和length属性之外,我们也不能使用任何循环,这是必须通过递归解决此问题的一种选择。我已经尝试过此功能,但仍然无法使用。

function getLength(string, length = 0){
  if (string[0] === undefined) {return length};
  length++;

  return getLength(length);
}

console.log(getLength("hello")) 
// expected answer: 5
javascript recursion string-length
3个回答
1
投票

您非常亲密。

function getLength(string, length = 0){
  if (string[length] === undefined) {return length};
  length++;

  return getLength(string, length);
}

console.log(getLength("hello")) 
// expected answer: 5

0
投票

您已经找到答案,只是错过了几个参数

function getLength(string, length = 0) {
  if (string[length] === undefined) {
    return length
  };
  length++;

  return getLength(string, length);
}

console.log(getLength("hello"))

0
投票

您可以定义递归的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"));
© www.soinside.com 2019 - 2024. All rights reserved.