JavaScript字典翻译函数仅返回首个结果,如何修复实现需求
现有代码存在的问题
- 未将输入的句子拆分为单词数组:直接遍历字符串
sentence[i]得到的是单个字符,不是完整单词,和字典的key匹配逻辑完全错误 - 内层循环增量变量写错:内层循环你写的是
i++而非j++,导致外层循环的计数变量i被意外累加,外层循环只执行一次就终止,所以只能拿到首个匹配结果 - 缺失异常处理逻辑:没有校验单词是否在字典中存在的分支,不符合返回错误信息的需求
- 没有封装为指定参数的函数:现有代码是零散的变量定义,不符合要求的入参为字典、句子的函数实现要求
修复后完整实现代码
function translate(dictionary, sentence) { // 把句子按空格拆分为单词数组 const wordList = sentence.split(' '); const translatedList = []; for (const word of wordList) { // 校验当前单词是否在字典中存在,规避原型链属性干扰 if (!dictionary.hasOwnProperty(word)) { return 'Error: missing value'; } translatedList.push(dictionary[word]); } // 拼接翻译后的单词为完整句子 return translatedList.join(' '); }
效果验证
题目给出的三个测试用例可直接验证,结果完全符合预期:
- 输入
translate({"je": "I","suis": "am","pere": "father","ton": "your"}, "je suis ton pere"),返回I am your father - 输入
translate({"the": "le","cute": "mignon","your": "ton","dog": "chien","is": "est"}, "the dog is cute"),返回le chien est mignon - 输入
translate({"the": "le","cute": "mignon","your": "ton","dog": "chien","is": "est"}, "the dog is fluffy"),返回Error: missing value
内容的提问来源于stack exchange,提问作者zbierek
相关产品推荐
相关产品推荐

