0

I have a array name in a string variable in JQuery. I want to get the array values from this string variable.

var f_1=["1","2","3","4"];
var f_2=["1","2","3","4"];
var f_3=["1","two","3","4",];
var f_4=["fname","lname","true","false","1"];       
var f_array=["f_1","f_2"];
populate_array();
function populate_array(){
        var x=f_array[0];
        var num= [];
        num=new Array(x).slice(0);          
        console.log("array values "+Array(f_1).slice(0));           
        for(var i=1;i<4;i++){               
            console.log(num[i]+"   "+f_array[0][i]);
        }
}

I am getting num as undefined and f_array[0][i] as _ , . How to assign the value of f_1 from f_array[0]?

Andreas
  • 2,455
  • 10
  • 21
  • 24
  • 1
    https://stackoverflow.com/questions/16282045/javascript-array-name-as-string-need-it-to-reference-the-actual-array – Batu.Khan Nov 07 '18 at 07:59
  • 1
    In 99% of cases where you are faced with having to refer to variables by their name, or when you have more than two variables with similar data, you should immediately realise what you are doing is probably wrong, and would be better using objects (or maps or arrays) instead. – Amadan Nov 07 '18 at 08:25

1 Answers1

0

keep in mind that this is not really smart thing to do but eval can solve your problem

var f_1=["1","2","3","4"];
var f_2=["1","2","3","4"];
var f_3=["1","two","3","4",];
var f_4=["fname","lname","true","false","1"];       
var f_array=["f_1","f_2"];

x=eval(f_array[0])
y=eval(f_array[1])
console.log(x)
console.log(y)
dbor
  • 1
  • 1
  • Keep also in mind that `eval` in JavaScript should realistically never be used. In overwhelming majority of cases you can do without dynamic string evaluation; in the minuscule remainder, `new Function(...)` is always a better choice. – Amadan Nov 07 '18 at 08:28