[英]Not able to understand why function returning undefined
I am creating a function to remove the underscore if it is the first character of the string.我正在创建一个函数来删除下划线,如果它是字符串的第一个字符。
The function converts the input to uppercase and get the first character and after a validation if requires it removes the first character.该函数将输入转换为大写并获取第一个字符,如果需要,则在验证后删除第一个字符。 Then again calling the same function with modified input to re validate.然后再次使用修改后的输入调用相同的函数以重新验证。 If it pass the condition I am returning the modified word from the else
.But somehow it is returning undefined
如果它通过了条件,我将从else
返回修改后的单词。但不知何故它返回undefined
let word = '__Hello_World'; function removeFirstUnderscore(ipWord) { // converting to uppercase and getting first character; let getFirstCharacter = ipWord.toUpperCase().charCodeAt(0); // 95 // now checking if first character is in this range between 65 & 95 if (getFirstCharacter <= 65 || getFirstCharacter >= 94) { // remove the first character & again call the recursive function to revalidate let removedFirstCharWord = ipWord.split('').splice(1).join(''); console.log('**** ', removedFirstCharWord); removeFirstUnderscore(removedFirstCharWord) } else { // if first character is within range then return it return ipWord; } } console.log(removeFirstUnderscore(word))
You have an if
statement.你有一个if
语句。
If the condition is not met, you return ipWord
.如果条件不满足,则return ipWord
。
If the condition is met, you call removeFirstUnderscore(removedFirstCharWord)
but return nothing.如果满足条件,则调用removeFirstUnderscore(removedFirstCharWord)
但不返回任何内容。
If you want to return the result of a recursive call, then you need to return
it.如果要返回递归调用的结果,则需要return
它。
return removeFirstUnderscore(removedFirstCharWord);
您需要在if
块中添加return
语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.