首页 > 解决方案 > 代码返回未定义而不是返回值

问题描述

我有字符串 101000 或 1010100 ,我试图在其中使用函数删除数据递归替换 100 。当字符串为空时,函数 removedata 应返回“yes”,当字符串不为空时返回“no”,同时将其替换为值 100。

它适用于字符串 1010100。它返回“no”,但不适用于字符串 101000,它变为空。

console.log(removedata("1010100"));
console.log(removedata("101000"));

function removedata(data) {
  data = data.replace("100", "");
  if (data.length == 0) {
    return "yes";
  } else {
    if (data.indexOf("100") > -1 && data.length > 0) {
      removedata(data);
    } else {
      return "no";
    }
  }
}

当 1010100 它返回 no 但是当 101000 它返回 undefined

标签: javascriptstringfunction

解决方案


您需要return递归调用:

console.log(removedata("1010100"));
console.log(removedata("101000"));

function removedata(data) {
  data = data.replace("100", "");
  if (data.length == 0) {
    return "yes";
  } else {
    if (data.indexOf("100") > -1 && data.length > 0) {
      return removedata(data);
    } else {
      return "no";
    }
  }
}

现在它返回yes第二个,因为所有的100s 都已被删除并且字符串为空。


推荐阅读