javascript将字符串作为函数调用
我在javascript中创建了一个i18n对象,如下所示,用于管理javascript文件中的语言javascript将字符串作为函数调用,javascript,string,function,eval,invoke,Javascript,String,Function,Eval,Invoke,我在javascript中创建了一个i18n对象,如下所示,用于管理javascript文件中的语言 i18n = { currentCulture: 'pt_PT', pt_PT : { message_key : "text in portuguese" }, en_US: { message_key : "text in english", },
i18n = {
currentCulture: 'pt_PT',
pt_PT : {
message_key : "text in portuguese"
},
en_US: {
message_key : "text in english",
},
/**
* translate
*/
__ : function(key,culture){
return this.culture.key;
},
/**
* returns the active user culture
*/
getUserCulture : function(){
return this.currentCulture;
},
/**
* sets the current culture
*/
setCulture : function(culture){
this.currentCulture = culture;
}
}
我需要根据translate函数的键和区域性参数返回正确的消息。
问题是在行中返回this.culture.key;javascript正试图在i18n对象中找到一种文化适宜性。
我如何调用它,例如this.pt\u pt.message\u键
谢谢你的帮助
感谢所有发布解决方案的人。我只能接受一个,所以我接受第一个。使用。假设区域性为“pt\u pt”,键为“message\u key”:
替换:
this.culture.key
与:
Javascript对象,您可以使用数组语法查找属性:
返回此[区域性][键] 与其说它叫数组语法,不如说它叫括号符号。
this.culture.key
this[culture][key]