How to convert a string value to a variable in javascript?

前端 未结 5 625
[愿得一人]
[愿得一人] 2021-01-27 09:46
var test1;
$(document).ready(function () {
    test1 = $(\"#test1ID\").jQueryPlugin();
});

var test2;
$(document).ready(function () {
    test2 = $(\"#test2ID\").jQuery         


        
5条回答
  •  花落未央
    2021-01-27 10:05

    If test1 is a global variable you can access it by name through the window object:

    window[theArrayOfStrings[0]].foo();   // test1();
    

    If it's not, eval is the only way, but I'd strongly advise avoiding eval in all circumstances. Using a lookup as in J-P's answer (+1) is much much more appropriate than selecting variable names.

提交回复
热议问题