2013-02-24 74 views
1

我想从我的html库中分离出语言变量,但我不确定这是什么最佳方法。解析js html库中的字符串(语言字符串)

目前我有这样的事情;

function putAlertA() { 
    alert('This is alert a'); 
} 

function putAlertB() { 
    alert('This is alert b'); 
} 

function setAlerts() { 
    putAlertA(); 
    putAlertB(); 
} 

现在我想琴弦从功能上分离:

溶液A

function putAlertA() { 
    var strings = getLanguageVars(); 
    alert(strings[0]); 
} 

function putAlertB() { 
    var strings = getLanguageVars(); 
    alert(strings[1]); 
} 

function setAlerts() { 
    putAlertA(); 
    putAlertB(); 
} 

function getLanguageVars() { 
    var strings = new Array(); 
    strings[0] = "This is alert a"; 
    strings[1] = "This is alert b"; 
    return strings; 
} 

溶液B

function putAlertA(strings) { 
    alert(strings[0]); 
} 

function putAlertB(strings) { 
    alert(strings[1]); 
} 

function setAlerts() { 
    var strings = getLanguageVars(); 
    putAlertA(strings); 
    putAlertB(strings); 
} 

function getLanguageVars() { 
    var strings = new Array(); 
    strings[0] = "This is alert a"; 
    strings[1] = "This is alert b"; 
    return strings; 
} 

搜索解决方案N c个

function putAlertA() { 
    var strings = window.strings; 
    alert(strings[0]); 
} 

function putAlertB() { 
    var strings = window.strings; 
    alert(strings[1]); 
} 

function setAlerts() { 
    putAlertA(); 
    putAlertB(); 
} 

window.strings = new Array(); 
strings[0] = "This is alert a"; 
strings[1] = "This is alert b"; 

我觉得C液将是最好的,因为我觉得液A &乙在内存消耗方面产生的开销太大,它看起来不合乎逻辑的,因为语言数组是一个全球变种。然而,我在使用window.时有点犹豫。不知道这是如何做到这一点的正确方法。也许有更好的方法如何做到这一点?我正在使用jQuery

+0

一些评论:1)不要使用'新的Array()'; 2)使用命名的字符串表(键对象具有一些含义)数组索引会变得混乱; 3)搜索,这个问题之前已经被问过很多次了。 – Chad 2013-02-24 14:10:41

+0

这是用于本地化吗? – 2013-02-24 14:10:53

+0

@Chad 1)我习惯用php和java来做新的Array(),JavaScript有区别吗?它甚至在W3schools上被推荐... 2)事情是,我得到了很多语言变量,这将使它更有可能是我不小心选择了一个已经存在的变量......而且我在选择新名称方面也不是很好哈哈哈3)你能给我一个链接?我搜索了它,但找不到它。也许是因为我不确定选择哪个关键字。 – bicycle 2013-02-24 14:18:48

回答

2

我更倾向于将静态对象,例如:

l10n = { 
    strings: [ 
     'alert_a': 'this is alert a', 
     'alert_b': 'this is alert b' 
    ], 
    translate: function(key) { 
     return this.strings[key]; 
    } 
} 

要拨打:

alert(l10n.translate('alert_a'); 

好有关这种方法的一个事情是,通过引入参数化的本地化字符串可以更容易地进行扩展,例如:

"Hello :name:" 

要拨打:

l10n.translate('key', { 
    name: 'world' 
}) 
// "Hello world" 
+0

这就像一个get/set!我喜欢那一个!我认为这也限制了内存方面的开销,因为你只打电话给你需要的东西 – bicycle 2013-02-24 14:20:51

+0

+1。我喜欢这种方法;尤其是因为你可以扩展到文化敏感的日期和数字格式。 – 2013-02-24 14:24:20

+0

@杰克我不会用它来用不同的语言。其他语言只是在不同的领域。当我在一个域上更新脚本时,我不想在另一个域上逐一编辑js文件。 – bicycle 2013-02-24 14:26:15

1

我要做的主要改变是使用字符串作为键而不是整数,因为这更有意义。这的确是选择一个好的变量名只是一个特殊情况:

window.strings = { 
     alertA: 'This is alert A', 
     alertB: 'This is alert B' 
    }; 

    alert(strings.alertA);