我正在尝试创建一个名为“trim”的函数来删除输入字符串头部和尾部的空格。 (我知道 String.prototype.trim 可以做同样的工作,我只是在练习我的 JS)但它返回“未定义”,你能帮助我吗?
function trim(str) {
if (str.charAt(0) === ' ') {
str = str.slice(1);
trim(str);
} else if (str.charAt(str.length - 1) === ' ') {
str = str.slice(0, -1);
trim(str);
} else {
return str;
}
}
console.log(trim(' ab c '));
最佳答案
您需要从递归的每个位置返回
,以确保您已将堆栈一路返回到原始调用者。请参阅下面的代码片段。
function trim(str) {
if (str.charAt(0) === ' ') {
str = str.slice(1);
return trim(str);
} else if (str.charAt(str.length - 1) === ' ') {
str = str.slice(0, -1);
return trim(str);
} else {
return str;
}
}
console.log(trim(' ab c '));
更多背景信息:
每次您从 trim
函数体内调用 trim
时,您都会 recursing 。如果您采用字符串 ' hello '
并将 trim
调用为 (trim(' hello ')
),则会发生以下情况:
- 调用
trim('hello')
。 - 满足第一个
if
条件 - 字符串被切片并调用trim('hello ')
。 - 满足第二个
if
条件 - 调用 string istrim('hello')
。 - 不满足
if
条件 - 进入else
block `返回“hello”。
所以我们的调用堆栈是trim('hello') ==>trim('hello')==>trim('hello')
。但是,在您最初编写的函数中,只有最后一次调用 trim
(trim('hello')
) 实际上向前一个调用者返回一个值 - trim
的其他调用不返回任何内容(未定义
)。为了确保返回值一直传递到 trim(' hello ')
的原始调用者,您需要确保每次递归时 return
递归的结果。
关于javascript - 我的 DIY trim 函数无法返回正确答案,它返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55653442/