How to access javascript variable value by creating another variable via concatenation?

前端 未结 4 791
醉话见心
醉话见心 2021-01-23 19:21

Please have a look on the following code -

var abc_text = \"Hello\";
var def_text = \"world\";

function testMe(elem) {
    var xyz = elem+\"_text\";
    alert(x         


        
相关标签:
4条回答
  • 2021-01-23 19:53
    var test={"abc":"Hello", "def":"World"};
    
    function testMe(elem) { 
        var xyz = test[elem];
        alert(xyz); 
    } 
    
    testMe("abc"); 
    testMe("def");
    

    0 讨论(0)
  • 2021-01-23 20:08

    You can eval xyz, but it's better to store abc_text and def_text in associative array or in object;

    
    var text = {"abc" : "Hello", "def" : "Word"};
    

    0 讨论(0)
  • 2021-01-23 20:08

    in this case use

    var xyz = window[elem+"_text"];
    
    0 讨论(0)
  • 2021-01-23 20:19

    There is a pretty good write-up on Dynamic Variables in JavaScript here:

    http://www.hiteshagrawal.com/javascript/dynamic-variables-in-javascript

    0 讨论(0)
提交回复
热议问题