You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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(' ');
}
效果验证

题目给出的三个测试用例可直接验证,结果完全符合预期:

  1. 输入translate({"je": "I","suis": "am","pere": "father","ton": "your"}, "je suis ton pere"),返回I am your father
  2. 输入translate({"the": "le","cute": "mignon","your": "ton","dog": "chien","is": "est"}, "the dog is cute"),返回le chien est mignon
  3. 输入translate({"the": "le","cute": "mignon","your": "ton","dog": "chien","is": "est"}, "the dog is fluffy"),返回Error: missing value

内容的提问来源于stack exchange,提问作者zbierek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 17:06:05