【问题标题】:Remove last name suffix with javascript recursive function使用javascript递归函数删除姓氏后缀
【发布时间】:2017-01-21 18:44:28
【问题描述】:

我想写一个这样的函数...

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"

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

【问题讨论】:

    标签: javascript recursion


    【解决方案1】:

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

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

    【讨论】:

    • 天哪 - 这很痛苦 - 谢谢/抱歉(我会在 5 分钟内接受答案)
    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 2017-06-05
    • 2020-11-17
    • 2011-12-02
    • 2021-06-09
    相关资源
    最近更新 更多