【发布时间】:2013-11-19 22:05:22
【问题描述】:
我正在尝试完成一个练习,但有些东西没有点击。
问题来了:您能否用 JS(或 Coffescript 或任何实际有意义的语言)编写一个方法 getTranslation(lang, path) --> 字符串,其工作方式如下: 你有这个全局对象:
strings = {
home: {
intro: {
en: 'Welcome',
fr: 'Bienvenue'
},
content: {
explanation: {
en: 'This is an interesting exercise',
fr: 'C\'est un exercice intéressant',
de: 'Es ist eine interesante Übung'
},
contact: 'Contact',
goodbye: {
en: 'Goodbye',
fr: 'Au revoir',
es: 'Adios'
}
}
}
}
和
getTranslation('home.intro', 'fr') // => 'Bienvenue'
getTranslation('home.content.contact', 'fr') // => 'Contact'
getTranslation('home.intro', 'es') // => 'Welcome'
getTranslation('home.content.goodbye') // => 'Goodbye'
getTranslation('unvalid.path','en') // => ''
所以第一个参数是一个字符串,它描述了通过点分隔的键的路径(不是假定的键中的点),第二个参数是语言,如果未提供或不存在,则回退到“en”(我们还假设在每个分支的末尾,要么存在“en”键,要么是单个字符串,如 home.content.contact)。
这是我到目前为止想出的答案,但我知道我做错了什么,因为没有返回任何内容。
function getTranslation (path, lang) {
lang = lang || "en";
var strings = {
home: {
intro: {
en: 'Welcome',
fr: 'Bienvenue'
},
content: {
explanation: {
en: 'This is an interesting exercise',
fr: 'C\'est un exercice intéressant',
de: 'Es ist eine interesante Übung'
},
contact: 'Contact',
goodbye: {
en: 'Goodbye',
fr: 'Au revoir',
es: 'Adios'
}
}
}
if (path == 'home.content.contact') {
return strings.path;
} else if (path == 'unvalid.path') {
return '';
} else {
return strings.path.lang;
}
}
getTranslation('home.intro', 'fr'); // => 'Bienvenue'
getTranslation('home.content.contact', 'fr'); // => 'Contact'
getTranslation('home.intro', 'es'); // => 'Welcome'
getTranslation('home.content.goodbye'); // => 'Goodbye'
getTranslation('unvalid.path','en'); // => ''
感谢任何愿意提供帮助的人。
【问题讨论】:
-
有很多方法可以做到这一点。你似乎要走的路径很乏味,因为你必须将你的路径与字符串 json 中的每个路径进行比较。
标签: javascript function logic