在Javascript中将字符串转换为变量

时间:2010-06-13 04:16:07

标签: javascript dynamic-data

有没有办法在Javascript中将字符串转换为变量?现在,我所拥有的是一个基于选择框值更新数据的脚本:

<script type="text/javascript">
var a = new Array();
a[0] = 'Name';
a[1] = 'Description';

var b = new Array();
b[0] = 'Name 2';
b[1] = 'Description 2';

function changeSystem(){
    var selectedAccount=document.getElementById('selected_option').value;

    document.getElementById('name').innerHTML = selectedAccount[0];
    document.getElementById('description').innerHTML = selectedAccount[1];
}
</script>
<form method="POST">
    <select onchange="changeSystem()" id="selected_option">
     <option>A</option>
     <option>B</option>
    </select>
</form>
<span id="name"></span><br>
<span id="description"></span><br>

selectedAccount<select>中所选元素的字符串。但是,要访问数组,它需要是一个变量,即a[0]而不是'a'[0]。有什么解决方案吗?

2 个答案:

答案 0 :(得分:4)

var dict = {
    'A': ['Name', 'Description'],
    'B': ['Name 2', 'Description']
};

dict['A'][0]

所以用

动态访问它
dict[selectedAccount][0]

您可以使用对象文字而不是数组:

var dict = {
    'A': {'name': 'john'}
};

dict['A']['name']

答案 1 :(得分:3)

我会使用类似的东西:

<script type="text/javascript">
var stuff = { 
    A: { name: 'Name', desc: 'Description'},
    B: { name: 'Name 2', desc: 'Description 2'}
};

function $(aId) {
    return document.getElementById(aId);
}

function changeSystem(){
    var selectedAccount = $('selected_option').value;

    if (selectedAccount in stuff) {
        $('name').innerHTML = stuff[selectedAccount].name;
        $('description').innerHTML = stuff[selectedAccount].desc;
    } else {
        $('name').innerHTML = '';
        $('description').innerHTML = '';
    } 
}
</script>
<form method="POST">
    <select onchange="changeSystem()" id="selected_option">
        <option>A</option>
        <option>B</option>
        <option>C</option>
    </select>
</form>
<span id="name"></span><br>
<span id="description"></span><br>

经过测试:Google Chrome 6.0.427.0 dev