将object(字典)和string(句子)作为函数形参,并从足够的键返回值



我必须做一个函数,接受字典(对象)和句子作为参数,并返回足够的键的值,如果字典函数中缺少单词,应该抛出错误"错误:missing value">

以下是输出的示例:

翻译({"je"我,"suis"","pere"father"你的";"你的";"你的";"你的";)//"我是你的父亲">

翻译({"the"le"cute"mignon"your"ton"dog"chien"是";;;;;;)//

翻译({"the"le"cute"mignon"your"ton"dog"chien"是";;;;;;)//'错误:缺少值'

我的代码是这样的:它的工作,但它停止在索引0,所以我只能得到第一个结果,即" i ">

let dictionary = {
"je": "I",
"suis": "am",
"pere": "father",
"ton": "your"
}
let dictKeys = Object.keys(dictionary)
let translated = []

for(let i=0; i < sentence.length; i++){
for(let j=0; j < dictKeys.length; i++){
if(sentence[i] == dictKeys[j]){
translated.push(dictionary[dictKeys[j]])
console.log(translated)
}
}
}

我不知道如何完成这个练习,请帮助我。

您的代码几乎没问题。在第二个循环中,您再次增加i而不是j。我添加了一个toLowerCase来覆盖区分大小写的单词

let dictionary = {
"je": "I",
"suis": "am",
"pere": "father",
"ton": "your"
}
let dictKeys = Object.keys(dictionary)
let translated = []
let missing = []
let sentence = "Je suis ton ami abc gfukgv".split(" ")
for (let i = 0; i < sentence.length; i++) {
if (!dictKeys.includes(sentence[i].toLowerCase())) {
missing.push(sentence[i])
//console.error(`"${sentence[i]}" word is missing from dictionary`)
}
for (let j = 0; j < dictKeys.length; j++) {
if (sentence[i].toLowerCase() == dictKeys[j].toLowerCase()) {
translated.push(dictionary[dictKeys[j]])
}
}
}
missing.length > 0 ? console.error(`The following words are missing from the dictionary: ${missing.join(", ")}`) : null
console.log(translated.join(" "))

最新更新