我的 DIY trim 功能无法 return 正确答案,它 return 无法解决
my DIY trim function cannot return correct answer, it returns undefied
我正在尝试创建一个名为 "trim" 的函数来删除输入字符串头部和尾部的空格。 (我知道 String.prototype.trim 可以做同样的工作,我只是在练习我的 JS)但是 return "undefined",你能帮帮我吗?
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 '));
您 return 仅在 else
子句上 str
。在任何情况下你都必须 return:
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);
}
return str;
}
您需要从递归的每个地方 return
,以确保您有 return 一路备份到原始调用者。请参阅下面的代码段。
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
条件 -- 字符串 trim('hello')
被调用。
- 不满足
if
条件-- else
块已进入 ` 'hello' 是 returned.
所以我们的调用栈是trim(' hello ') ==> trim('hello ') ==> trim('hello')
。但是,在您最初编写的函数中,只有最后一次调用 trim
(trim('hello')
) 实际上 return 是前一个调用者的值 - [=12= 的其他调用] return 没有(undefined
)。为了确保值 return 一直传递回 trim(' hello ')
的原始调用者,您需要确保每次递归 return
的结果递归。
我正在尝试创建一个名为 "trim" 的函数来删除输入字符串头部和尾部的空格。 (我知道 String.prototype.trim 可以做同样的工作,我只是在练习我的 JS)但是 return "undefined",你能帮帮我吗?
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 '));
您 return 仅在 else
子句上 str
。在任何情况下你都必须 return:
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);
}
return str;
}
您需要从递归的每个地方 return
,以确保您有 return 一路备份到原始调用者。请参阅下面的代码段。
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
条件 -- 字符串trim('hello')
被调用。 - 不满足
if
条件--else
块已进入 ` 'hello' 是 returned.
所以我们的调用栈是trim(' hello ') ==> trim('hello ') ==> trim('hello')
。但是,在您最初编写的函数中,只有最后一次调用 trim
(trim('hello')
) 实际上 return 是前一个调用者的值 - [=12= 的其他调用] return 没有(undefined
)。为了确保值 return 一直传递回 trim(' hello ')
的原始调用者,您需要确保每次递归 return
的结果递归。