javascript - 使用javascript递归函数删除姓氏后缀

标签 javascript recursion

我想编写一个采用这样名称的函数...

Dan Smith Jr
Kim Johnson II
Dr Jones PHD
Bill Clinton

并返回姓氏...

Smith
Johnson
Jones
Clinton

我的解决方案是将字符串中的最后一个词切掉,将其与停用词数组进行比较,然后递归循环直到停用词数组中不存在一个词...

var fullNameArray;
var lastName;
var suffixArray = ["jR","Jr","JR","jr","I","II","III","i","ii","iii","PHD","PHd"]; //list of stopword prefixes

function getLastName(fullName){
    fullNameArray = fullName.split(" ");
    lastName = fullNameArray[fullNameArray.length - 1]; //got the last word

    if (suffixArray.indexOf(lastName) == -1) {
        //it's NOT a suffix so RETURN the name
        console.log("returning last name of: " + lastName);
        return lastName;
    } else {
        //it WAS a suffix so call the function again with the last name chopped off
        fullNameArray.pop(); //remove the last item
        getLastName(fullNameArray.join(" "));
    }
}

我的问题是递归调用没有按预期工作:

getLastName("Dan Smith") 正确返回:

 "returning last name of: Smith"
 "Smith"

getLastName("Dan Smith Jr") 返回...

 "returning last name of: Smith"
 "undefined"

在递归调用中 return 不起作用,我犯了什么错误?!!

最佳答案

需要返回递归调用函数的结果:

return getLastName(fullNameArray.join(" "));

关于javascript - 使用javascript递归函数删除姓氏后缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41783093/

相关文章:

javascript - 我如何使用 javascript 来警告这些 PHP 错误消息?

javascript - 调整窗口大小时自动将图像适合 div 容器

javascript - 使用 jQuery 发布

c++递归调用不将项目推送到 vector

javascript - 使用||函数返回值中的运算符

java - 如何使代码递归地向后打印?

javascript - AngularJS - 如何访问嵌套 ng-repeat 中的数组

javascript - Firebase 调用 update() 数据库引用 javascript 时的路径无效

javascript - request-promise-native 的替代方案

module - OCaml 中的递归集