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

时间:2017-01-21 18:44:29

标签: 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"

我在递归电话中为返回工作做出了什么错误?!!

1 个答案:

答案 0 :(得分:4)

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

DataPortal