我想让一个变量看到它的值是另一个变量的名称并取其数组

时间:2017-03-18 00:11:30

标签: javascript arrays variables

var t1 = document.getElementById('t1').value;

var t2 = document.getElementById('t2').value;

var VA = ["VA", 4, 10.8, 18];

var DE = [3, 10.9, 6];

var GA = [77, 23.3, 8];

var AA = [21, 11, 2];

var KS = [23, 10.3, 3];

var LE = [2, 11.7, 7];

var NA = [11, 14.3, 5];

var UA = [71, 15.1, 16];

我有一些上面的代码,我的第一个变量t1将具有我的任何其他变量(不包括t2)的字符串值,我希望它能够看到并能够使用其他数组。

t1或t2将具有输入的值,例如VA或DE

例如

t2可能被称为GA

对于我的代码,我希望它看到t2是GA和cahnage t2到上面的变量GA。

1 个答案:

答案 0 :(得分:1)

您应该将这些变量创建为对象属性。以下是该解决方案的工作原理:



var t1 = document.getElementById('t1');
var out = document.getElementById('out');

var vars = {
    VA: ["VA", 4, 10.8, 18],
    DE: [3, 10.9, 6],
    GA: [77, 23.3, 8],
    AA: [21, 11, 2],
    KS: [23, 10.3, 3],
    LE: [2, 11.7, 7],
    NA: [11, 14.3, 5],
    UA: [71, 15.1, 16]
};

t1.oninput = function() { 
    var name = t1.value;
    var value = vars[name];
    // Use value in any desired way.
    out.textContent = JSON.stringify(value);
}

Variable: <input id="t1"> (example: "VA")<br>
Content: <span id="out"></span>
&#13;
&#13;
&#13;

或者,当您输入两个输入和就地替换时:

&#13;
&#13;
var t1 = document.getElementById('t1');
var t2 = document.getElementById('t2');

var vars = {
    VA: ["VA", 4, 10.8, 18],
    DE: [3, 10.9, 6],
    GA: [77, 23.3, 8],
    AA: [21, 11, 2],
    KS: [23, 10.3, 3],
    LE: [2, 11.7, 7],
    NA: [11, 14.3, 5],
    UA: [71, 15.1, 16]
};

t1.oninput = t2.oninput = function(e) { 
    var name = e.target.value;
    if (name in vars) {
        var value = vars[name];
        // Use value in any desired way. 
        e.target.value = JSON.stringify(value);
    }
}
&#13;
Variable 1: <input id="t1"> (example: "VA")<br>
Variable 2: <input id="t2"> 
&#13;
&#13;
&#13;