我正在尝试完成一项练习,但有些事情就是没有点击。
问题是:你能否用 JS(或 Coffescript 或任何真正有意义的语言)编写一个 getTranslation(lang, path) --> string 方法,其工作方式如下: 您有这个全局对象:
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'); // => ''
感谢任何愿意提供帮助的人。
最佳答案
不确定这是否是最好的解决方案,但它满足您的所有需求。
function getTranslation(path, lang) {
lang = lang || "en";
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'
}
}
}
}
path = path.split(".");
var result = strings;
for(var i in path){
result = result[path[i]];
if(result == undefined){
return '';
}
}
return (result[lang]==undefined)?"":result[lang];
}
关于javascript - 根据函数参数返回嵌套对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20083057/