我想编写一个采用这样名称的函数...
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/