【发布时间】: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