javascript - 代码返回未定义而不是返回值
问题描述
我有字符串 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
解决方案
您需要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
第二个,因为所有的100
s 都已被删除并且字符串为空。
推荐阅读
- sql - 按区域访问扩展工作表
- python - DataFrame.to_csv 抛出错误“[Errno 2] 没有这样的文件或目录”
- ruby-on-rails - 乐观锁定是否适用于使用 update_all 中的 updated_at 属性的以下代码?
- dart - Flutter - 删除飞镖中的转义序列
- java - 添加对象 onStartPage itextPdf 除了最后一页
- math - 语料库分数计算
- c# - Dynatrace OneAgent 如何更改 dotnet 应用程序 HTTP 标头
- python-3.x - 异质化numpy数组,使得没有两个相邻的单元格相等
- appium - Appium 中的此元素无法进行交互
- runtime-error - RAD Studio 10.2 (C++):~TControl() 析构函数仅适用于每第二次迭代